Functions
Functions
let a = function(){
console.log("a called");
}
a();
// First class functions:- The language where function can be treated like as other
variable is called first class functions.
In such language functions
or
function square(num){
return num * num;
}
function displaySquare(fn){
console.log("square is " + fn)
}
displaySquare(square(5))
Return a function
---------------------
function sayHello(){
return function(){
console.log("hello")
}
}
sayHello()
IIFE?
(function(num){
console.log(num*num);
})(5)
Ex. What will be the op?
(function(x){
return (function(y){
console.log(x);
})(2)
})(1)
Function scope?
Variables defined inside a function cannot be accessed from anywhere outside the
function.
A function can access all variables and functions defined inside the scope in which
it is defined.
Hoisting?
Functions are hoisted Entirely
But in case of variable it's defination is only hoisted.
console.log(x) // undeifned
var x = 10
hi() // hi.....
function hi(){
console.log("hi.....")
}
Q. Params Vs Arguments
Q.
function fn(a,b){
return a * b;
}
let arr = [4,5]
fn(...arr); // spread operator
The values will pass from array to function as arguments
Q.
op:- [4,5]
Q.
function fn(x,y,...nums){
console.log(x,y,nums);
}
fn(1,2,3,4,5,6,7);
op:- 1 2 [3, 4, 5, 6, 7]
Callback functions:-
Its a function, passed to another function as an argument.
Arrow functions:-
Arguments keyword is not there in arrow function
function fn(){
console.log(arguments)
}
fn(1,2,3,4,5,6,7);
But
let fn = () => {
console.log(arguments)
}
fn(1,2,3,4,5,6,7);