// function Expression:- When you store a function inside of a variable it is
called as function expresion
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
1. assigned as a value to a variable
2. passed an argument to another function
3. can be returned by another function
Assign a function to variable
-----------------------------
let b = function(){
console.log("b called");
}
a();
pass a function as argument
-----------------------------
function square(num){
return num * num;
}
function displaySquare(fn){
console.log("square is " + fn(5))
}
displaySquare(square)
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()
High order function:
A function that returns a function is called a Higher-Order Function.
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
Because its only defination is hoisted
hi() // hi.....
function hi(){
console.log("hi.....")
}
Because entire function is hoisted
Q. Params Vs Arguments
function fn(a,b){ // params
return a * b;
}
fu(2,3) // 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.
function fn(...nums){ // rest operator
console.log(nums);
}
let arr = [4,5]
fn(...arr);
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.
addEventListener(),setTimeout(), map(), filter() are the examples
Arrow functions:-
Arguments keyword is not there in arrow function
function fn(){
console.log(arguments)
}
fn(1,2,3,4,5,6,7);
OP:- Arguments(7) [1, 2, 3, 4, 5, 6, 7, callee: ƒ, Symbol(Symbol.iterator): ƒ]
But
let fn = () => {
console.log(arguments)
}
fn(1,2,3,4,5,6,7);
OP:- ReferenceError: arguments is not defined
This issue in Arrow function:-
let user = {
name: "sam",
fn1: () => {
console.log(this.name);
},
fn2(){
console.log(this.name);
}
}
user.fn1(); // ''
user.fn2(); // 'sam'