Skip to main content

Command Palette

Search for a command to run...

JavaScript : Function Declaration vs Function Expression

Updated
2 min readView as Markdown
JavaScript : Function Declaration vs Function Expression

Lets understand function as var can store the value same as function store the single or multiple line of code which we can use where we need.

Instead of writing the same code again and again, you wrap it inside a function and call it whenever needed.

like:

function add(a, b) {// syntax for creating function with vars 
  return a + b; // now code for adding 2 numbers
}
// now we call function with values which we need to perform action
console.log(add(2, 3)); // 5
// add is function and 2,3 are the values of 'a' and 'b' which functions required

as we see above this is function declaration,

Function Type

  • function declartion

  • function expression

//function declation as we already seen lets discuss both again
// Function Declaration
function add(a, b) {
  return a + b;
}

// Function Expression just same as above but it store in var
const addExp = function(a, b) {
  return a + b;
};

console.log(add(2, 3));     // 5 // calling way is the same 
console.log(addExp(2, 3));  // 5 // for function declation and expression

Hoisting

hosting is the issue when fuction call before creation.

  • function declaration never create this issue

  • function expression has the issue of hoisting because it store it the variable

console.log(multiply(2, 5)); // ✅ works

console.log(multiplyExp(2, 5)); // ❌ error

function multiply(a, b) {
  return a * b;
}

const multiplyExp = function(a, b) {
  return a * b;
};
// both works here
console.log(multiply(2, 5)); // ✅ works

console.log(multiplyExp(2, 5)); //✅ works

Hoisting means JavaScript moves declarations to the top

Feature Function Declaration Function Expression
Syntax function name() const name = function()
Hoisting ✅ Yes ❌ No
Use Before Definition ✅ Works ❌ Error

Summary

Functions is block of code which can process the different values which can be used in multple places which different values.

Use Function Declaration:

  • When you want to define reusable functions early

  • When you may call it before writing it

  • simple, hoisted, beginner-friendly

Use Function Expression:

  • When assigning functions to variables

  • When using functions as values (common in modern JS)

  • flexible, used more in modern JavaScript