Function কী?
Function হলো পুনরায় ব্যবহারযোগ্য কোডের ব্লক।
৩ ধরনের Function
// ১. Function Declaration
function greet(name) {
return `হ্যালো, ${name}!`;
}
console.log(greet("করিম"));
// ২. Function Expression
const greet2 = function(name) {
return `হ্যালো, ${name}!`;
};
// ৩. Arrow Function (ES6) ⭐
const greet3 = (name) => `হ্যালো, ${name}!`;
// Arrow function variants
const add = (a, b) => a + b; // implicit return
const square = x => x * x; // ১ প্যারামিটার কোষ্ঠক ছাড়া
const sayHi = () => console.log("Hi"); // প্যারামিটার নেই
const complex = (a, b) => {
let sum = a + b;
return sum * 2;
};
Default Parameters (ES6)
function greet(name = "Guest", greeting = "হ্যালো") {
return `${greeting}, ${name}!`;
}
greet(); // "হ্যালো, Guest!"
greet("করিম"); // "হ্যালো, করিম!"
greet("করিম", "শুভ সকাল"); // "শুভ সকাল, করিম!"
Rest Parameters
function sum(...numbers) {
return numbers.reduce((a, b) => a + b, 0);
}
sum(1, 2, 3); // 6
sum(1, 2, 3, 4, 5); // 15
Spread Operator
let arr1 = [1, 2, 3];
let arr2 = [4, 5, 6];
let combined = [...arr1, ...arr2]; // [1,2,3,4,5,6]
let obj1 = { a: 1, b: 2 };
let obj2 = { ...obj1, c: 3 }; // { a:1, b:2, c:3 }
Scope (স্কোপ)
// Global scope
let x = 10;
function outer() {
// Function scope
let y = 20;
function inner() {
// Nested scope
let z = 30;
console.log(x, y, z); // সবগুলো access করতে পারে
}
inner();
}
// Block scope (let/const)
if (true) {
let a = 5;
const b = 10;
}
console.log(a); // ❌ ReferenceError
Closure
function counter() {
let count = 0;
return function() {
count++;
return count;
};
}
const myCounter = counter();
myCounter(); // 1
myCounter(); // 2
myCounter(); // 3
// count ভেরিয়েবলটি বাইরে নেই কিন্তু inner function এর মনে আছে
IIFE (Immediately Invoked Function Expression)
(function() {
console.log("তৎক্ষণাৎ চলে!");
})();
// Arrow version
(() => console.log("Hi"))();