Challenge your understanding of block scope and function scope distinctions in JavaScript with realistic scenarios and key concepts. This quiz helps clarify how variable declarations using var, let, and const behave within different contexts.
If a variable is declared with var inside a function, which scope does it have?
Explanation: Declaring a variable with var inside a function gives it function scope, meaning it is accessible anywhere within that function. Block scope does not apply to var declarations, only to let and const. Variables with global scope are declared outside any function or block. Module scope is not created by var; it relates to imports and exports in modules.
In the following snippet, which scope does the variable x have? for (let x = 0; x u003C 5; x++) { /* ... */ }
Explanation: The variable x declared with let inside the loop has block scope, so it only exists within the loop block. Function scope does not apply here, because let does not hoist to the containing function. Global scope means the variable is accessible everywhere, which is not the case. Script scope is not a recognized term for this context.
Which statement about redeclaring variables is true regarding function and block scope?
Explanation: let variables cannot be redeclared in the same block scope because doing so causes a syntax error. var variables can be redeclared both in the same function and globally, though it is discouraged. const variables cannot be redeclared in the same block, as they are also block scoped and constant. Therefore, only the first statement is correct.
What is the result if you try to access a let-declared variable outside the block in which it was defined?
Explanation: Accessing a let-declared variable outside its block causes a ReferenceError because it does not exist in that scope. Unlike var, let is not hoisted in a way that makes it accessible before its declaration or outside its block. Returning the last assigned value is incorrect, as the variable does not exist in that context. A SyntaxError is not thrown at access time, only at declaration if there is an error.
If a variable with the same name is declared with var in a function and let in an inner block, what describes this scenario?
Explanation: Within the inner block, the let variable shadows any outer variable (including those declared with var) with the same name so only the block-scoped variable is accessible there. Both variables do not refer to the same value in all scopes—the block and function scopes are separate. The var variable cannot shadow the let variable within the block, since block scope is tighter. This scenario does not cause a syntax error because they are declared in different scopes.