DEV Community

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

Posted on

3

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.

Image of Docusign

🛠️ Bring your solution into Docusign. Reach over 1.6M customers.

Docusign is now extensible. Overcome challenges with disconnected products and inaccessible data by bringing your solutions into Docusign and publishing to 1.6M customers in the App Center.

Learn more

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more