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.
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));
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.
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.
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!