Arrow Function vs Normal Method
this binding:
Arrow function:
Does not has its own
thiskeyword, it inheritsthisfrom the surrounding lexical scope where it was defined.This feature is particularly useful when working with callbacks, as the context in which the function is created may differ from the context in which it is called
(a) Declared in the Global Context
const arrowFunction = () => { console.log(this); }; // Arrow functions do not have their own `this` arrowFunction(); // `this` refers to the surrounding lexical scope (global in this case)(b) Inside an Object
const obj = { value: 42, arrowFunction: () => { console.log(this); }, }; obj.arrowFunction(); // `this` still refers to the surrounding scope, not `obj` (global or outer context)(c) Nested Inside a Normal Function
const obj = { value: 42, normalFunction: function () { const arrowFunction = () => { console.log(this); }; arrowFunction(); // `this` refers to `obj` because it inherits from the surrounding `normalFunction` }, }; obj.normalFunction(); // `this` is `obj`
Normal function:
The value of
thisis dynamic and depends on how the function is called.It can change when the function is invoked using
.call,.apply, or.bind.(a) Function Declaration
function normalFunction() { console.log(this); } // Calling it in the global context normalFunction(); // In browsers: `window`, in Node.js: `global`(b) Function Expression
const normalFunction = function () { console.log(this); }; // Calling it in the global context normalFunction(); // In browsers: `window`, in Node.js: `global`(c) As a Method of an Object
const obj = { value: 42, normalFunction: function () { console.log(this); }, }; obj.normalFunction(); // `this` refers to `obj`(d) Extracted from an Object
const extractedFunction = obj.normalFunction; extractedFunction(); // `this` is `undefined` in strict mode or `window/global` in non-strict mode
Arguments Object
Normal Method:
- Has access to the
argumentsobject, which is an array-like object containing all the arguments passed to the function. (How come I just got to know about this?!!)
- Has access to the
javascriptCopy codefunction normalFunction() {
console.log(arguments);
}
normalFunction(1, 2, 3); // [1, 2, 3]
Arrow Function:
- Does not have its own
argumentsobject. To access arguments, you must use rest parameters.
- Does not have its own
javascriptCopy codeconst arrowFunction = (...args) => {
console.log(args);
};
arrowFunction(1, 2, 3); // [1, 2, 3]