function declarations in JavaScript

In JavaScript functions can be declared with function statements, anonymous functions and arrow functions.

They all accomplish the same thing by allowing you to put code in one place to prevent the same logic from being repeated.

function statement

The function statement starts with the keyword function with a name after it.

JavaScript

function greet (name) {
  console.log('hello, ' + name);
}

greet('brian');
// hello, brian

Function statements are hoisted so it can be executed before it was declared.

JavaScript

greet('brian');
// hello, brian

function greet (name) {
  console.log('hello, ' + name);
}

anonymous function

It has the same syntax as a regular function statement but a name isn’t needed.

JavaScript

const numbers = [10, 5, 4, 3];

const doubleArr = numbers.map(function (number) {
  return number * 2;
});

console.log(doubleArr);
// [20, 10, 8, 6]

Anonymous functions is a shorter way to declare functions.

A name can be added to the function and it will work the same.

JavaScript

const numbers = [10, 5, 4, 3];

const doubleArr = numbers.map(function double(number) {
  return number * 2;
});

console.log(doubleArr);
// [20, 10, 8, 6]

Adding a name to a function in a callback could be useful because if there is an error it will show up on the stack trace.

JavaScript

const numbers = [10, 5, 4, 3];

const doubleArr = numbers.map(function doubleNumber (number) {
  throw 'error: something went wrong';
  return number * 2;
});

console.log(doubleArr);
// [20, 10, 8, 6]
stack trace error example

arrow function

Arrow functions is the shortest way a function can be declared.

this is defined by where the arrow function is declared instead of where it is being executed.

JavaScript

const arrowFunction1 = (greeting) => {
  return `${ greeting } Brian`;
}

// shortest way to declare arrow function
// the expression is automatically returned
// if there is only one argument the parenthesis are not required
const arrowFunction2 = greeting => `${ greeting } Brian`;

arrowFunction1('hello');
// 'hello Brian'

arrowFunction2('hi');
// 'hi Brian'

Conclusion

There are three ways to declare functions function statement, anonymous function and arrow function.

anonymous functions and arrow functions are often used as callback to a function.

javascript
shadowing objects properties in javascript

when creating a property on a object that has the same property name on its prototype it will shadow it.

javascript
filter an array with another array

Filtering an array with another array is useful when you have many elements you want to remove from an array.