Different ways to define a function in JavaScript.

Functions in JavaScript

function typeCheck() {};
typeCheck instanceof Function // Logs True

Function declaration

function sum(param1, param2) {
return param1 + param2;
}
  • A variable that holds the function object is created in the current scope with the same identifier as the function name provided — in our example, sum.
  • The variable is hoisted to the top of the current scope.
console.log(notYetDeclared()); // Logs 'Here!'function notYetDeclared() {
return 'Here';
}

Function expression

let sum = function(param1, param2) {
return param1 + param2;
};
console.log(notYetDeclared); // Logs 'undefined'let notYetDeclared = function() {
return 'Here';
}

Arrow functions

let sum = (param1, param2) => {
return param1 + param2;
};
let sum = (param1, param2) => param1 + param2;
let double = param1 => param1 * 2;

Generator function

function* idMaker() {
let index = 0;
while(true)
yield index++;
}let gen = idMaker();console.log(gen.next().value); // Logs 0
console.log(gen.next().value); // Logs 1
console.log(gen.next().value); // Logs 2

Function Constructor

let sum = new Function('param1', 'param2', 'return param1 + param2');

Conclusion

  • If you want to leverage function hoisting, use function declarations
  • Arrow functions are well suited for short callback functions and, more importantly, when the desired this is the enclosing function.
  • Avoid using the Function constructor to define functions. If the annoying syntax wasn’t enough to keep you away, it is extremely slow because the function gets parsed each time it’s called.

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store