Closures and Scope
1. What is lexical scope in JavaScript?
Lexical scope মানে হলো — একটি variable কোথায় access করা যাবে, সেটা নির্ধারিত হয় সেই variable টি code-এ কোথায় লেখা হয়েছে তার উপর ভিত্তি করে, runtime-এ কোথায় call হচ্ছে তার উপর নয়।
সহজ কথায়: "কোড লেখার সময়ই scope নির্ধারিত হয়ে যায়।"
JavaScript-এ প্রতিটি function বা block তার চারপাশের (outer/parent) scope-এর variable গুলো access করতে পারে। এটাই lexical scoping।
function outer() {
const message = "Hello from outer!"; // outer scope-এ define করা
function inner() {
console.log(message); // ✅ inner function, outer-এর variable access করতে পারে
}
inner();
}
outer(); // Output: "Hello from outer!"
এখানে inner function টি message variable-টি নিজের scope-এ না থাকলেও, lexical parent (অর্থাৎ outer) থেকে সেটি access করতে পারছে।
🔍 Scope Chain
Lexical scope কাজ করে scope chain তৈরির মাধ্যমে। কোনো variable খুঁজে না পেলে JavaScript inner → outer → global — এই ক্রমে উপরে উঠতে থাকে।