Syntax for declaring functions

In much of the bootcamp, functions have been declared using this syntax:

function checkScope() {
blah blah blah
}

But when discussing arrow functions, there is another syntax presented:

var magic = function() {
  blah blah blah
};

The second uses the declaration keywords let, var, or const, and the first does not. Is there a substantial difference here? Is one syntax preferred over the other?

1 Like

Oof… another complex question! (Love them!)

So first of all, I would strongly advise dropping use of the ‘var’ for variable declaration. You will come across them in older code and examples, but for newer code going forward, you should use let/const and ignore var completely.

So the function in this block

var magic = function() {
  blah blah blah
};

is a function expression, the format above is called an anonymous function (as the function itself has no name) . Note that it is possible to assign a name to the function in a function expression too, which helps during debugging. Please refer to the section here:

You will encounter anonymous functions very often, either in the above form, or as a lambda function (which were introduced in ESS6). They are widely used in functional programming, and patterns that were popularized by React. A lot of JS functions can accept a function as argument, and you will see often an anonymous function used as drop-in. That kind of use is explained here:

Lastly, a decent post with naming and examples may help your understanding further:

I hope this helps?

3 Likes

Again, super, super helpful. I think what confused me about these being “anonymous” functions is that they are still being stored in a variable, so that variable still felt like the function’s name. Now I see that there are contexts where naming the function by storing it in a variable is not necessary. This video also helped me understand a clear context for when you might pass a function into another function as an argument, an idea that made my head spin when I first read your post.

In the bootcamp, it seems that these anonymous functions are always being called with arguments, and so calling an anonymous function looks exactly like calling a named function, i.e. add(3, 4);, if one were to call the last function declared in the tutorial you linked. But now I see that if a function doesn’t need an argument, then a function call looks indistinguishable from any other variable (since it doesn’t need parentheses for its empty argument).

2 Likes

This topic was automatically closed 45 days after the last reply. New replies are no longer allowed.