DEV Community

Cover image for function declaration vs function expression
Himanshu Gupta
Himanshu Gupta

Posted on

function declaration vs function expression

In JavaScript, there are two common ways to define a function: function declaration and function expression.

A function declaration is a statement that declares a named function with a specified set of parameters. Here's an example:

function addNumbers(a, b) {
  return a + b;
}
Enter fullscreen mode Exit fullscreen mode

A function expression, on the other hand, is an assignment statement where the function is assigned to a variable or property. Here's an example:

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

The main difference between function declaration and function expression is that function declarations are hoisted to the top of their scope, whereas function expressions are not.

This means that you can call a function declared with a function declaration before it is defined in the code, but you cannot do the same with a function expression. For example:

console.log(addNumbers(2, 3)); // Output: 5

function addNumbers(a, b) {
  return a + b;
}
Enter fullscreen mode Exit fullscreen mode

In this case, the function addNumbers is hoisted to the top of the code, so it can be called before it is defined.

However, if you try to do the same with a function expression, you will get an error:

console.log(addNumbers(2, 3)); // Output: Uncaught ReferenceError: addNumbers is not defined

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

In general, it's a good practice to use function declarations for functions that need to be called before they are defined, and function expressions for functions that will be assigned to variables or properties.

→ But function expression can only invoke/run/call "after" the function definition.

→ If we call the function expression before initialization, then this will give an error.

→Function declarations are hoisted but function expressions are not.

Top comments (0)