Scope & closures

Computer Science · JavaScript

Question 1 of 10

0

    let y; console.log(y); What is logged?

    Stuck? Read the explanation

    Unlocks at a streak of 5 correct answers in a row.

    Print a free worksheet (PDF)

    Embed this practice on your site or class page

    Paste this HTML into your page. Students practise right there; it is free and needs no account.

    Scope & closures explained

    Scope decides where a variable can be used. A closure is a function that keeps access to the variables of the scope where it was created, even after that scope has finished running.

    JavaScript uses lexical scope: a function can read variables from its own body and from every enclosing scope, but not the reverse. Name lookup starts in the innermost scope and moves outward, so an inner variable can shadow an outer one with the same name.

    function makeCounter() {
        let count = 0;
        return () => {
            count = count + 1;
            return count;
        };
    }
    const next = makeCounter();
    console.log(next(), next(), next());
    

    A closure forms when an inner function uses outer variables and outlives the outer call. The inner function keeps a live link to those variables rather than a copy, which allows private state. Each call of the outer function creates new variables, so separate counters do not share state.

    Worked example

    makeCounter runs once and creates count = 0. Each call to next adds 1 to that same count, so the three calls return 1, 2 and 3. A second counter from another makeCounter() call would start its own count at 0.

    What you will practise

    100 multiple-choice questions (Easy, Medium, Hard). Each answer is followed by an explanation.

    Example questions

    • A closure:
    • A closure forms when:
    • Closures enable:
    • A closure keeps variables:
    • Lexical scope means the closure sees:
    • Which keyword declares a variable that is block-scoped in JavaScript?
    • What does the term 'scope' describe in JavaScript?
    • A const variable declared inside a function body can normally be used:

    …and 92 more.