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.