function Keyword
Functions are reusable blocks of code.
Define them with function
(declaration or expression) or with arrow functions () => ...
.
They can take parameters, return values, and be async.
Syntax
// Declaration (hoisted)
function add(a, b) {
return a + b;
}
// Function expression
const mul = function (a, b) {
return a * b;
};
// Arrow function
const sub = (a, b) => a - b;
// Default & rest parameters
function greet(name = "Guest", ...tags) {
console.log("Hello", name, tags);
}
// Async function
async function load(url) {
const res = await fetch(url);
if (!res.ok) throw new Error("Bad response");
return await res.text();
}
Examples
// ১) বেসিক প্যারামিটার ও ফেরত
ফাংশন গ্রেড(নম্বর) {
যদি (নম্বর >= 80) ফেরত "A+";
নাহলে যদি (নম্বর >= 70) ফেরত "A";
নাহলে ফেরত "A-এর নিচে";
}
ছাপাও(গ্রেড(85));
// ২) ডিফল্ট & রেস্ট প্যারামিটার
ফাংশন লগ(লেভেল = "info", ...বার্তা) {
কনসোল.লগ("[", লেভেল, "]", ...বার্তা);
}
লগ(); // [ info ]
লগ("warn", "সতর্কতা", 42);
// ৩) অবজেক্ট ডেস্ট্রাকচারিং প্যারামিটার
ফাংশন ইউজার({ নাম, শহর = "Dhaka" }) {
ফেরত `${নাম} @ ${শহর}`;
}
দেখাও(ইউজার({ নাম: "Mamun" }));
// ৪) হায়ার‑অর্ডার ফাংশন (map/filter)
const সংখ্যা = [1, 2, 3, 4, 5];
const জোড় = সংখ্যা.filter(n => n % 2 === 0);
const বর্গ = সংখ্যা.map(n => n * n);
কনসোল.লগ(জোড়, বর্গ);
// ৫) রিকার্শন
ফাংশন ফ্যাক্টোরিয়াল(n) {
যদি (n <= 1) ফেরত 1;
ফেরত n * ফ্যাক্টোরিয়াল(n - 1);
}
কনসোল.লগ(ফ্যাক্টোরিয়াল(5));
Notes
- Declarations are hoisted; expressions/arrow are not (bindings exist but
let/const
are in the TDZ). - Arrow functions don’t have their own
this
,arguments
, orprototype
; avoid using them as constructors or methods needing dynamicthis
. - Default parameters evaluate at call time; rest collects remaining args into an array.
- Prefer early returns to reduce nesting; name functions for clearer stack traces.
- Deep recursion may overflow—convert to loops or use stacks where necessary.
- Keep language style consistent per file (English/Bangla/Banglish).