Arrow functions ਛੋਟੇ ਹਨ, ਪਰ ਅਸਲ ਵਿੱਚ ਫਰਕ binding behavior ਵਿੱਚ ਹਨ, ਸਿਰਫ syntax ਵਿੱਚ ਨਹੀਂ।
const regular = function () {};
const arrow = () => {};
const short = x => x * 2; // implicit return for one expression
Arrow functions ਛੋਟੇ ਹਨ, ਪਰ ਅਸਲ ਵਿੱਚ ਫਰਕ binding behavior ਵਿੱਚ ਹਨ, ਸਿਰਫ syntax ਵਿੱਚ ਨਹੀਂ।
const regular = function () {};
const arrow = () => {};
const short = x => x * 2; // implicit return for one expression
1. ਆਪਣਾ this ਨਹੀਂ — arrows ਆਲਦ ਦੇ scope ਤੋਂ this ਪ੍ਰਾਪਤ ਕਰਦੇ ਹਨ। ਇਹ ਸਭ ਤੋਂ ਮਹੱਤਵਪੂਰਨ ਫਰਕ ਹੈ ਅਤੇ ਇਸੇ ਕਾਰਨ ਉਹ callbacks ਲਈ ਸ਼ਾਨਦਾਰ ਹਨ:
const timer = {
seconds: 0,
start() {
setInterval(() => this.seconds++, 1000); // ✅ `this` is timer
// a regular function here would have its own `this` (undefined) → bug
},
};
2. arguments object ਨਹੀਂ — ਇਸਦੀ ਥਾਂ rest parameters ਵਰਤੋ:
const sum = (...args) => args.reduce((a, b) => a + b, 0);
3. Constructors ਵਜੋਂ ਵਰਤਿਆ ਨਹੀਂ ਜਾ ਸਕਦਾ — new arrow() throw ਕਰਦਾ ਹੈ, ਅਤੇ ਉਨ੍ਹਾਂ ਕੋਲ ਕੋਈ prototype ਨਹੀਂ ਹੈ।
const obj = {
name: "Ann",
greet: () => `Hi ${this.name}`, // ❌ `this` is NOT obj (it's outer scope)
greet2() { return `Hi ${this.name}`; }, // ✅ method needs dynamic `this`
};
Object methods ਲਈ arrows ਨਾ ਵਰਤੋ (ਉਹ object ਨੂੰ bind ਨਹੀਂ ਹੋਣਗੇ) ਜਾਂ ਜਦੋਂ ਤੁਹਾਨੂੰ dynamic this/arguments ਦੀ ਲੋੜ ਹੋਵੇ (event handlers ਜੋ this ਨੂੰ element ਵਜੋਂ ਭਰੋਸੇ ਤੇ ਕਰਦੇ ਹਨ)।
Callbacks ਅਤੇ ਛੋਟੀਆਂ ਫੰਕਸ਼ਨਾਂ ਲਈ arrows ਵਰਤੋ ਜਿੱਥੇ this ਪ੍ਰਾਪਤ ਕਰਨਾ ਉਹੋ ਹੈ ਜੋ ਤੁਸੀਂ ਚਾਹਦੇ ਹੋ; methods, constructors, ਅਤੇ prototype methods ਲਈ ਆਧੁਨਿਕ functions ਵਰਤੋ।
ਵਿਸਤ੍ਰਿਤ ਜਵਾਬਾਂ ਨਾਲ IT ਇੰਟਰਵਿਊ ਸਵਾਲਾਂ ਦੀ ਇੱਕ ਲਾਇਬ੍ਰੇਰੀ — ਜੂਨੀਅਰ ਤੋਂ ਸੀਨੀਅਰ ਤੱਕ।
ਦਾਨ ਕਰੋ