Function Declaration vs Function Expression
Functions-
functions enclose a piece of code within them that perform a certain task.
They provide us with the following :-
Enclose a block of code inside a reusable unit
Keep code cleaner and organized
Avoid repetition (DRY principle – Don’t Repeat Yourself)
Improve readability and maintainability
Reuse logic multiple times
Write once , use many times
Function declaration
A function declaration defines a named function using the function keyword.
function getSum(a, b) {
console.log("sum: " + (a + b));
}
getSum(2, 4); // function call
getSumis the function nameaandbare parameters (inputs to the function){}contains the block of code that runs when the function is calledgetSum(2, 4)is the function call, where2and4are arguments
Returning a value
Instead of just printing the result, we can return it using the return keyword.
function getSum(a, b) {
return a + b;
}
const sum = getSum(2, 4);
console.log(sum); // 6
returnsends the result back to where the function was calledIt allows us to store the result in a variable
The function stops executing once
returnrunssumwill hold the valuereturnedbygetSumfunction.
Function Expression
A function expression stores a function inside a variable.
const addition = function getSum(a, b) {
return a + b;
}
getSum();
Here:
The function is assigned to a variable
The variable name is used to call the function
Difference between declaration and expression
Hoisting -
Declaration syntax - The declaration syntax gets hoisted i.e the function can be called even before its declared, lifted by javascript to the top of the file before running.
Expression syntax (NOT Hoisted) - since in this syntax , the function will be held inside a variable. It won't be executed until execution reaches that line
// declaration
sayHi(); // works
function sayHi() { console.log("Hi!"); }
// expression
sayBye(); // crash
const sayBye = function() { console.log("Bye!"); };
Usage | |
Declaration | want a global function that can be used anywhere |
Expression | want to keep code structured, scoped, or passed into other functions. |