Scope Chains u0026 Variable Lookup Quiz Quiz

Explore the mechanics of scope chains, variable resolution, and lookup in nested functions with this focused quiz. Enhance your understanding of variable access and shadowing in programming through practical questions and scenarios.

  1. Variable Access in Nested Functions

    Given the code: function outer() { var x = 10; function inner() { return x; } return inner(); }, what value is returned when outer() is called?

    1. null
    2. undefined
    3. ReferenceError
    4. 10

    Explanation: The inner function can access the variable x from its parent (outer) scope, so calling outer() returns 10. 'undefined' and 'null' are incorrect because x is properly declared and initialized. 'ReferenceError' would only occur if x did not exist in any scope, which isn't the case here.

  2. Variable Shadowing and Lookup

    In the code: let y = 5; function demo() { let y = 20; return y; } What value does demo() return?

    1. 5
    2. ReferenceError
    3. 25
    4. 20

    Explanation: Within the demo function, a new y variable is declared, which shadows the one in the outer scope, so the function returns 20. The value 5 is incorrect as it's not in the local scope. 'ReferenceError' would only occur if y was not defined anywhere, and '25' is a distractor with no basis in the code.

  3. Understanding Unresolved Variables

    If you try to access a variable not defined in any accessible scope, such as calling console.log(z) with no definition of z, what is the result?

    1. ReferenceError
    2. 0
    3. undefined
    4. null

    Explanation: Accessing a completely undeclared variable causes a ReferenceError because the variable cannot be found in any scope chain. Returning 'undefined' or 'null' is incorrect because those values apply to declared but uninitialized variables. 0 is unrelated in this context.

  4. Scopes and Parameter Names

    Given: function calc(a) { var b = 4; function add(a) { return a + b; } return add(3); } What value is returned by calc(2)?

    1. 6
    2. 7
    3. 8
    4. 5

    Explanation: The inner add function uses its own parameter a, which is 3, not the outer a. 'b' from outer scope is 4, so the result is 3 + 4 = 7. '6' mistakenly uses the outer a. '5' ignores b's value, and '8' adds all numbers together, which is incorrect.

  5. Function Scope vs. Block Scope

    Consider: function testScope() { if (true) { var c = 10; } return c; } What is returned when testScope() is called?

    1. ReferenceError
    2. NaN
    3. 10
    4. undefined

    Explanation: Variables declared with 'var' are function-scoped, not block-scoped, so c is accessible throughout the entire function and returns 10. 'undefined' and 'NaN' are incorrect as c is defined and numeric. 'ReferenceError' would only result if c were undeclared, which isn't the case here.