Variables (var/let/const)

Computer Science · JavaScript

Question 1 of 10

0

    What does this JavaScript code log? let x = 17; x = x * 5; x += 8; console.log(x);

    Decimals (0.75 or 0,75), fractions (3/4) and mixed numbers (1 1/2) are accepted. Do not use thousands separators.

    How to type your answer
    • Fractions: 3/4. Mixed numbers: 1 1/2.
    • Decimals with a point or a comma: 0.75 or 0,75.
    • Negative numbers start with a minus: -3/4.
    • Percentages need the % sign: 75%.

    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.

    Variables (var/let/const) explained

    JavaScript has three keywords for declaring variables: var, let and const. They differ in where the variable is visible and whether it can be reassigned.

    var is the oldest form. A var declared inside a function is visible throughout that function, and block braces do not limit it. It is hoisted, so the name exists before its line runs, but its value is undefined until the assignment.

    let creates a variable limited to its surrounding block, such as an if body or a loop body, and it can be reassigned. const also creates a block-scoped variable, and it must be given a value when declared. It cannot be reassigned, but this applies to the binding, not the value: a const array can still have items pushed onto it.

    const price = 4;
    let count = 3;
    count = count + 1;
    const items = [];
    items.push(price * count);
    console.log(items[0]);
    

    Most modern code uses const by default and switches to let only when a value must change.

    Worked example

    Trace the program above. price stays 4. count starts at 3 and is reassigned to 4. The array is empty, and push adds 4 × 4 = 16. The program logs 16. Writing price = 5 later would throw a TypeError.

    What you will practise

    New numbers every time you practise. Levels: Easy, Medium, Hard. Each answer is followed by a worked explanation.

    Example questions

    • Easy

      What does this JavaScript code log?

      let x = 7; x = x * 8; x += 2; console.log(x);

    • Medium

      What does this JavaScript code log?

      let v = 36; { let v = 57; } console.log(v);

    • Hard

      What does this JavaScript code log?

      let x = 30; let y = 0; { let x = 2; y = x + 18; { x = x * 2; } } console.log(x + y);