Search This Blog

2023/04/27

Lambda function vs traditional function

In JavaScript, there are several differences between traditional functions
and lambda functions (also known as arrow functions):

1)arguments binding:
Arguments objects are not available in arrow functions, but are available
in regular functions.
Example1:

let myFunc = {
showArgs(){
console.log(arguments);
}
};
myFunc.showArgs(1, 2, 3, 4);

Output:
1,2,3,4

Example2:
let myFunc = {
showArgs : ()=> {
console.log(arguments);
}
};
myFunc.showArgs(1, 2, 3, 4);
Output:arguments is not defined

2)Arrow functions cannot be called with new:

ES6 distinguishes between functions that are callable and functions that are
constructible.

If a function is constructible, it can be called with new, i.e. new User().
If a function is callable, it can be called without new (i.e. normal function
call).

Regular functions created through function declarations / expressions are both
constructible and callable.

Example 3:
let x = function(){
console.log(arguments);
};

new x(1,2,3,4)

Output:
[Arguments] { '0': 1, '1': 2, '2': 3, '3': 4 }

Example 4:
let x = ()=> {
console.log(arguments);
};
new x(1,2,3);

Output:x is not constructor

3) this binding:

Unlike regular functions, arrow functions don’t have their own this or
arguments binding.
Instead, those identifiers are resolved in the lexical scope

Unlike regular functions, arrow functions do not have their own this.
In the case of an arrow function, this refers to the values of this in
the environment the arrow function is defined in (i.e. "outside" the
arrow function) and that remains the same throughout the lifecycle of
the function and is always bound to the value of this in the closest
non-arrow parent function.

Example 5:
function createObject(){
console.log("Inside createObject:",this.foo)
return {
foo:42,
bar:function(){
console.log("Inside bar:",this.foo)
}
}
}

createObject.call({foo:21}).bar()

Output:
Inside createObject: 21
Inside bar: 42


Example :
function createObject() {
console.log("Inside createObject:", this.foo)
return {
foo: 42,
bar: () => {
console.log("Inside bar:", this.foo)
}
}
}

createObject.call({ foo: 21 }).bar()

Output:
Inside createObject: 21
Inside bar: 21

No comments:

Post a Comment