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
Function declaration loads before any code is executed, while a Function expression loads when the interpreter reaches that line of code.
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:
you need to create a more readable and understandable function.
you need to create a function that is recursive (a recursive function is a function that calls itself).
you need to call the function before it is defined.
Use a Function expression when:
you need a reusable function.
the function should be used when it is defined.
you need a function that isn't hoisted (Hoisting explained).
you want to control when the function is executed
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.
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.