There are only few different ways to declare functions in JS and I thought this topic wouldn’t be worth a blog post. But the ninja mentions some details I wasn’t aware of.

Functions in JS are always initiated by the function keyword. What comes afterwards is either a name, or nothing. If there is nothing, it is called an anonymous function. Big surprise. Anonymous functions make sense only if you don’t want to reference this particular function anywhere else in your code ever again.

But if what your function is supposed to do is something you want to do repetitively, like let’s say, making coffee, it is probably a good idea to give that function a name. Even better, giving it a name that tells something about what the function does. You might name a function “coffeeMachine” and instruct it with all necessary steps for a good brew. After having done that, any time you are feeling in the mood for a coffe, you can simple call out: “Hey, coffeeMachine do what you know best” as often as you want, without having to reinstruct with each single step again. That is what you’d have to do , if you’d have declared it as an anonymous function, no simple button to press.

But there is more to the difference of named and anonymous functions. Declaring a function like this:


function coffeeMachine1 () {
  var cupOfCoffee = 'A cup of Coffee 1';
  return cupOfCoffee;
};

or this:


var coffeeMachine2 = function () {
  var cupOfCoffee = 'A cup of Coffee 2';
  return cupOfCoffee;
};

seems to be almost the same, but isn’t.

Both variants are returning a nice cup of coffee, but, coffeeMachine1 is a declared function with a name. Whereas coffeeMachine2 is a declared variable that has an anonymous function as value. The function itself however has no name.
Testing this difference in ninja style looks like this:


assert(typeof window.coffeeMachine1 === 'function', 'Is coffeeMachine1 a function?');
assert(typeof window.coffeeMachine2 === 'function', 'Is coffeeMachine2 a function?');

assert(coffeeMachine1.name === 'coffeeMachine1', 'Does coffeeMachine1 have a name?');
assert(coffeeMachine2.name === 'coffeeMachine2', 'Does coffeeMachine2 have a name?');

// and for my private pleasure, because I simply need these silly logouts:
console.log(coffeeMachine1());
console.log(coffeeMachine2());

And in my neat browser view, you can see that the first three of the four tests pass fine to green, but the last one fails, the variable has a name, but the function does not:

so many coffees

Why is that important?

Depending on how a function is declared, it’s availability differs, and that is of importance. The coffee machine’s button is not equally accessible for all ways of declarations, which has to do with what’s called scope in JS.

That’s going to be my next blog post’s topic.