Skip to main content

Command Palette

Search for a command to run...

Function Declaration vs Function Expression: What’s the Difference?

Basic guide of defining a function in javascript by two types.

Updated
•2 min read•View as Markdown
Function Declaration vs Function Expression: What’s the Difference?

What is Function?

We can say that a function is a wrapper above the logic that you will perform again and again. Benefits of function is clean code,code reuse and easy to maintain.

Without Function

console.log(2 + 3)
console.log(5 + 7)
console.log(10 + 4)

With Function:

function add(a, b) {
  return a + b
}

console.log(add(2,3))
console.log(add(5,7))
console.log(add(10,4))

Here the add function can be used multiple times

Functions can be defined by 2-types in javascript.

1.Function Declaration

2.Function Expression

1.Function Declaration

Here function is declared with the name, and later called with the function name.

Function Declaration:

function add(a, b) {
  return a + b
}

console.log(add(2,3)) // 5

2.Function Expression

Here the function is stored in a variable and later the variable is used to call the function

Function Expression:

let add = function(a, b) {
  return a + b
}

console.log(add(2,3)) // 5

Hoisting Issue in Function Expression

Function Declaration If the function call is above its body, still the function can be executed but in the function expression body needs to be hoisted in it and later you can call the variable.

Function Declaration:

sayHello()

function sayHello() {
  console.log("Hello")
}

OUTPUT: Hello

Function Expression:

sayHello()

let sayHello = function() {
  console.log("Hello")
}

OUTPUT: Output: “SayHello” cannot be executed before initialization

This are the Difference between the function declaration and function expression.

Thank You!!!