JavaScriptFunctions & Scope
Q7. What are arrow functions and how do they differ from regular functions?
Arrow function-এর সুবিধা ও সীমাবদ্ধতা, regular function থেকে পার্থক্য — উদাহরণসহ।
Arrow function হলো ES6-এ আসা সংক্ষিপ্ত ফাংশন লেখার নতুন উপায় — ফাংশন keyword লেখার বদলে => তীর চিহ্ন বসে। এটি মূলত একটি অ্যানোনিমাস ফাংশনের শর্টহ্যান্ড, তাই ছোট কাজে দারুণ সুবিধাজনক।
তিন প্রকার লেখার ধরনjavascript
javascript
// regular function
function add(a, b) {
return a + b;
}
// arrow function — একই কাজ, ছোট লেখায়
const add2 = (a, b) => {
return a + b;
};
// আরও ছোট — এক লাইনে return ছাড়াই
const add3 = (a, b) => a + b;
// একটি প্যারামিটার হলে বন্ধনীও লাগে না
const square = (n) => n * n;
const square2 = (n) => n * n;
console.log(add(2, 3), add2(2, 3), add3(2, 3)); // 5 5 5
console.log(square(4), square2(4)); // 16 16সবচেয়ে বড় পার্থক্য হলো `this`-এর আচরণ। Arrow function-এর নিজস্ব this নেই — সে বাইরের scope থেকে this ধার করে নেয়।
this-এর পার্থক্যjavascript
javascript
const user = {
name: "Rahim",
regular: function () {
return this.name; // Rahim — নিজস্ব this
},
arrow: () => this.name, // undefined — this ধার করেছে
};
console.log(user.regular()); // Rahim| বিষয় | Regular function | Arrow function |
|---|---|---|
this | নিজের this | বাইরের this ধার করে |
arguments | নিজস্ব | থাকে না |
| নিজের prototype | থাকে | থাকে না |
new দিয়ে তৈরি | যায় | যায় না |
| hoisting হয় | হ্যাঁ | না |
সরাসরি return ছাড়া | লাগে | এক লাইনে লেখা যায় |
সতর্কতা
অবজেক্টের method হিসেবে arrow function ব্যবহার করলে this কাজ করবে না, কারণ সেটি ট্রিকি ধরে ফেলবে না। অবজেক্টের method লাখার জন্য regular function বা class method ব্যবহার করুন।
শেষ প্যারায় নিজে practice করুন — কোড কপি করে নিজের এডিটরে চালিয়ে দেখুন।