DEV Community

Discussion on: JavaScript Functions: a breakdown.

Collapse
 
pentacular profile image
pentacular

In this example, funcName is being invoked BEFORE the function is declared, and will result in an error saying the function is not defined.

This works just fine for me, and I rather thought this was the point of hoisting.

funcName();
function funcName() {
  // do something;
}

My understanding is that with hoisting, the above example is re-arranged to the below form.

function funcName() {
  // do something;
}
funcName();

Which is why it does not produce an error.

Function Expressions are not hoisted, so this would prevent those icky instances of a Function Expressions getting invoked before it gets hoisted and stashed in memory.

Perhaps not, but var declarations are, so ...

funcName();
var funcName = function ()  { /* do something */ };

is re-arranged to

var funcName;
funcName();
funcName = function () { /* do something */ };

Which does have the problem you described above, since var declarations are hoisted, but not the initializations, and we get something like "TypeError: funcName is not a function".

Arrow Functions are a Syntactic extension of Function Expressions

I'm not entirely sure you can reasonably call them a syntactic extension, since they have different semantics.

But since the Arrow Functions use the curly braces by default, they can't differentiate between a block scope and an object literal and would result in an error.

Well, your example won't result in an error, but it may be surprising when it always returns undefined.

const setColour = colour => {value: colour };

console.log(setColour('blue'));

value is a perfectly good label, and colour is a perfectly good expression, after all.

The moral of the story being that it's always a good idea to test your examples to see if they actually do what you expect. :)

Collapse
 
coopercodes profile image
🧸 🏳️‍🌈 cooper-codes 💻 🎮

Thanks for the feedback, I’ll review this tomorrow morning and edit

Collapse
 
pentacular profile image
pentacular

You're welcome. :)