A function might be a staple object in programming, but you might see them written many different ways in JavaScript, even within the same code base — this is because functions have different properties depending on how they were defined.

This is a field guide to the different types of functions you might encounter on your JavaScript programming journey, derived from documentation from the MDN Web Docs.

Overview

The syntax a function is written in determines these properties: whether or not it is hoisted, named, has an implicit return, or lexically binds the value of the this keyword.

I made this graph to summarize what we’re working with:

Note: Both Functions and Generator Functions can be created using their respective object constructors, but this is not recommended.

Function Declarations

I have found this to be the most common way functions are written in plain ol’ vanilla JavaScript. Here is an example:

cow() // => "moo"

function cow() {return "moo"}

Note that the function can be invoked before it is declared because its definition is put into memory during compilation, before the code is executed.

For function declarations, as well as all of the other types of functions except arrow functions, the value of the this keyword changes depending on its execution context. In ES2015 the .bind(someObj)method allows you to permanently set the value of this as the object passed into .bind.

function f() {
  return this.a;
}

var g = f.bind({a: 'azerty'});
console.log(g()); // azerty

var h = g.bind({a: 'yoo'}); // bind only works once!
console.log(h()); // azerty

var o = {a: 37};
console.log(o.a, o.f(), o.g(), o.h()); // 37,37, azerty, azerty

(modified from: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this)

Function Expressions

Function expressions, unlike function declarations, do not have to be named and are not hoisted.

Unnamed, or anonymous functions, are popularly used as callbacks because they are immediately invoked. However, the MDN Web Docs notes that it is still useful to name your functions to make it easier to trace them in your call stacks.

const dog = function() { return "bark" }

dog() //=> "bark"
(function() {return "meow"})() //=> "meow"

You cannot reuse immediately invoked functions even if they are named.

(function sheep() { return "baa" })() // => "baa"

sheep() // => ReferenceError: sheep is not defined

#javascript #functions-in-javascript #programming #programming-languages

The Many Ways to Write JavaScript Functions
1.35 GEEK