ecabigting
← Back to Blog

Different Ways To Declare Functions in Javascript

by Eric Thomas D. Cabigting
Different Ways To Declare Functions in Javascript

Function Declaration

  • Using the `function` keyword
  • These functions are hoisted on top of the scope where you defined them. Which enables you to use the functions even if they are declared at the end of your code.
JavaScript
function foo(bar) {
  return bar-1;
}

Function Expressions

  • Also using the `function` keyword
  • You are assigning it to a `variable` that can be use later on
  • Difference of Expressions vs Declarations is that the Function Expressions are not hoisted to the top of the global scope
JavaScript
const myValue = function myFunction(foo,bar) {
  return bar * foo;
}

Another variation of this is a nameless function directly assigned to a variable like below:

JavaScript
const addition = function(val1,val2){
  return val1 + val2;
}

Functions Expressions in Objects

  • Assigning a nameless functions in a property of an object
JavaScript
const mdas = {
  mul: function(val1,val2) {return val1 * val2;},
  div: function(val1,val2) {return val1 / val2;},
  add: function(val1,val2) {return val1 + val2;},
  sub: function(val1,val2) {return val1 - val2;},
}

Continue Reading.