Skip to main content

Command Palette

Search for a command to run...

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

Updated
2 min read

In JavaScript, functions are reusable blocks of code that perform a specific task. They help organize logic, reduce repetition, and keep the code DRY (Don't Repeat Yourself).

For example:

function printMe (){
console.log("me")
}

Functions can be created in different ways. Two common ways are function declarations and function expressions.

Understanding the difference between them helps you write cleaner and more flexible code.

Function Declaration

A function declaration is the process of creating a function where you declare a function name and write the function logic inside curly braces {}.
These functions are hoisted, which means we can use them before their definition in the code.

function sumTwoNumbers(num1,num2){

return num1+ num2

}

Example of calling the function before its definition:

console.log(sumTwoNumbers(4, 5)); // 9

function sumTwoNumbers(num1, num2) {
  return num1 + num2;
}

Function Expression

A function expression is a function that is assigned to a variable.
These functions are not hoisted, which means you cannot use them before their declaration.

const greeting =  function(name){
return `hello ${name}`;
}
console.log(greeting("John"));

Example of calling the function before its definition:

console.log(greeting("John")); // error

const greeting =  function(name){
return `hello ${name}`;
}