Lesson 1 of 80
Where a variable can be seen from — and why JavaScript decides that by where you wrote the code, not where it runs.
12 min read
Every option explains itself — why the right one is right, and why each wrong one is wrong. Miss one and it comes back later on a spaced-repetition schedule.
Question 1 of 2
Why can a function read a variable from the file's top level, but the top level can't read a variable declared inside that function?
Hints without spoilers, and a plain explanation of why a wrong answer was wrong — answered only from this lesson. Free account, no card.
Sign up freeWhat interviewers actually ask about this, and what a strong answer has to cover.
A strong answer covers
Likely follow-ups
Scope answers one question: from here, which variables can I see?
Think of scope like rooms in a house. Code inside a room can see everything in its own room and in the rooms it's nested inside — but not what's tucked away inside sibling rooms.
The word lexical just means "decided by where the code is written." JavaScript works out scope by reading the source, before anything runs — not by who calls what at runtime.
Every time you write a function, you open a new room:
const appName = "Praxis"; // outer room
function greet() {
const user = "Adesh"; // inner room
return `Hi ${user}, welcome to ${appName}`; // can see both
}
// console.log(user); // ReferenceError — the outer room can't see inside
greet can reach outward to appName, but the outside can't reach inward to user. That one-way visibility is the whole game.
Two rooms: the outer one (the file) holds appName. The inner one (greet) holds user.
var ignores block scope. A var declared inside an if leaks to the whole function. let and const respect the surrounding block.let or const variable exists from the top of its block, but you can't touch it until the line that declares it — accessing it early throws, it isn't undefined.If you can explain lexical vs dynamic scope and why the temporal dead zone exists, you've already signalled more depth than most candidates. The natural follow-up is closures — which is exactly where we go next.