Skip to main content

Command Palette

Search for a command to run...

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

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

Introduction

In every programming language we use the functions to perform our tasks easily & make our code base clean & structured

What functions & why we need them

Functions is nothing it is a reusable block of code that can be used anywhere whenever we want to perform a task/action

Syntax :

function functionName(params){
//Code
}

Function Declaration syntax

Function declaration means we are just declaring a function and using it in future wherever we want just by the function name

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

Using the function

console.log(add(3,5))

Output :

8

Function expression syntax

Function expression is the another way to create a function in JavaScript by just storing the declared function in a variable

Function expression:

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

Using the function

console.log(addition(2,4))

Output :

6

Function declaration Vs function expression

The one major difference in both is

Function Declaration are hoisted

Function expression are NOT hoisted

What is hoisting ?

Hoisting in JavaScript is a mechanism where the functions, and classes are conceptually moved at the top of the scope allow us to using the function before declaration

When to use each type ?

Function declaration :

Is used when we want to use or access that function globally

Function Expression :

Is used when we want to limit the access or usage of that function in a scope

Conclusion

Both function declaration & function expression are the methods in JavaScript to use function(reusable block of code), It depends our need that we want to limit the access of our function or not, we want the fixed scope for our function or not, So Both have an advantage depends on usage...

3 views