Also called function defination or function statement.
function square(num){
return num*num;
}
When a function is stored in a variable.
const square = function(num){
return num*num;
}
Where a function can be treated like a variable, those functions are called first class function.
These functions can be passed into another functions can be manipulated and returned from those function. Basically a variable can do.
So functions are first class function in JS.
function square(num){
return num*num;
}
function displaySquare(fun){
console.log("square", fun(5));
}
displaySquare(square);
Immediately invoked function expression
(function square(num){
console.log(num*num);
})(5);
(function (x){
return (function (y){
console.log(x); // 1
})(2);
})(1);
for(let i =0 ; i<5 ; i++){
setTimeout(function(){
console.log(i); // 01234
}, i*1000);
}
for(var i =0 ; i<5 ; i++){
setTimeout(function(){
console.log(i); // 44444
}, i*1000);
}
Functions are hoisted completely to the top of their scope.
We have global scope of x.
In local scope x is present.
Hoisting is 2 step process:
1. First is initialize the complete code. (init global scope.)
2. Then it init local scope (first host this variable in top of this scope) So in this scope. x is present and is undefined right now.
If we have variable in local scope we dont go to global scope.
function square(num){ // num is params
return num*num;
}
square(5); // 5 is argument
A function passed into another function as an argument. Which is then invoked inside the outer function.
map, filter, settimeout, reduce