Function Declarations Vs Function Expressions

It's necessary for a developer who is new to JavaScript functions to understand the difference between function declarations and function expressions. This article will shed more light on them.

Function Declaration

Function declarations are just normal functions. They are also referred to as function statements. A few things to note about them are:

a. They must have a function name.

b. They are standalone constructs

c. Functions in the function declaration can be accessed before and after the function definition.

/* Function Declaration syntax */

function addNum (paramA, paramB) {
  //set of statements
}
function myFunction(a1,  a2) {
  console.log(a1 * a2);
}
myFunction(2, 3);  //This line can also be placed above the function

//Logs out '6' to the console

Function Expression

Function expression :

a. does not have function names

b. can be stored in a variable assignment

c. can load only when the interpreter reaches the line of code

// Function Expression syntax

var addNum = function(paramA, paramB) {
   //set of statements
}
var addNum = function (a, b) {
  console.log(a + b);
}
addNum(5, 7); //This line can only be placed after the function

Live code on how Functions are used

Main Differences

  1. Function declaration loads before any code is executed, while a Function expression loads when the interpreter reaches that line of code.

  2. Function expressions are stored in a variable assignment.

When to Choose a Function Declaration Vs a Function Expression

Wondering when to choose between a function declaration and a function expression?

Below are a few guidelines to help make a quick decision.

Use a Function declaration when:

  1. you need to create a more readable and understandable function.

  2. you need to create a function that is recursive (a recursive function is a function that calls itself).

  3. you need to call the function before it is defined.

Use a Function expression when:

  1. you need a reusable function.

  2. the function should be used when it is defined.

  3. you need a function that isn't hoisted (Hoisting explained).

  4. you want to control when the function is executed

  5. the function is anonymous.

Conclusion

As we've seen, both functions are similar and they share almost the same syntax. Whichever one you decide to use is totally fine.

21
Subscribe to my newsletter

Read articles from Deborah Fabusuyi directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Deborah Fabusuyi
Deborah Fabusuyi

I am Fabusuyi Deborah, but you can call me "Dherrbie". I am a Junior frontend developer, that is passionate about building responsive websites and bringing life to Designs. I'm also passionate about breaking down complex topics into simple and concise articles for Technical and Non-technical readers.