DEV Community

Cover image for Javascript: Function Declaration vs Function Expression
Anojan Thevarasa
Anojan Thevarasa

Posted on

Javascript: Function Declaration vs Function Expression

Functions in Javascript are a block of code that execute an action/operation. Functions can take in parameters while being defined and later the parameters shall be passed as arguments while calling. There are, however, two ways in which a function is defined in Javascript based on when the particular function should be executed. One is called Function Declaration and the other way is Function Expressions. There are some differences in the defining and behaviour of the two methods.

Function Declaration
Function declaration is defining a function right off with the keyword "function" followed by function name, with or without parameters. The syntax for function declaration is:
function exampleFunction (param1,param2, etc){
//action to execute
}

Here's an example function declaration that takes in two int values for parameters and returns the sum of them:

function addition(a,b){
  return sum = a + b
}
Enter fullscreen mode Exit fullscreen mode

Function Expression
This is the way in which functions are defined and equaled(stored in) to a variable name usually with the keyword const. And later the variable name containing the function can be called. Syntax for a function expression is as follows:

const functionName = function(param1,param2,etc) {
// action to execute
}

The same example sum function from above can be defined in an expression as follows:

const addition = function(a,b){
  return sum = a + b
}
Enter fullscreen mode Exit fullscreen mode

Major Difference
Both function declaration and function expression are used in Javascript and its frameworks based on some factors, the main of which is the time when a function has to be called for execution. By default, function declarations are hoisted, i.e. they take the top of the order of execution in a block of code irrespective of where they are defined. This way a function can be called either before or after it is defined.

On the other hand, a function expression is not hoisted. A function defined through expression is usually executed only in the order of where it is defined, in accordance with the synchronous nature of Javascript. Such a function can be called for execution only after it is defined and not before.

Top comments (0)