Articles
- Function Expressions vs Function Declarations — Paul Wilkins
- JavaScript Function — Declaration vs Expression — Ravi Roshan
- Function Declarations vs. Function Expressions — Mandeep Singh
- Function Declarations vs. Function Expressions — Anguls Croll
Expressions vs Statement
Function declarations are hoisted, but function expressions aren't. Precisely, variable assigned to function expressions are hoisted, but it's uninitialized, so we can't use it before we assgin it.
Expressions
After function expression has stored in a variable, variable can be used as a function, which means that it is invoked by variable's name
let sum = function(num1, num2){
return num1 + num2;
};
console.log(sum(1,2));
When to use function expressions
- Closure
function checkValid(input) {
const password = "password123";
return function() {
if(input === password) {
console.log("verified!");
} else {
console.log("wrong!");
}
}
}
checkValid("password123")(); // verified!
checkValid("password1234")(); // wrong!
console.log(password); // ReferenceError: password is not defined
In this snippet, function expression is used for closure that is closing over variable password
. Although, we cannot access to this variable in global scope, we can use the inner function inside checkValid
function which can still access to password
. By using closure, we can hide the password
, but can still check if the input is valid.
- Passing as arguments
function checkSum(num1, num2, callback) {
if(callback(num1, num2) == num1 + num2) {
return "It's sum function!";
} else {
return "Error";
}
}
const sum = function(num1, num2) {
return num1 + num2;
}
console.log(checkSum(2,3,sum)); // It's a sum function!
Function checkSum
checks if the given function is a sum function. By using function expression, we made function sum
and it's given as a parameter to checkSum
function.
- IIFE IIFE helps preventing functions and variables from affecting the global scope.
const checkValid = ((input) => {
const password = "password123";
return function(input) {
if(input === password) {
console.log("verified!");
} else {
console.log("wrong!");
}
}
})();
checkValid("password123"); // verified!
checkValid("password1234"); // wrong!
Top comments (0)