Code tracing: "what does this log?"

Computer Science · JavaScript

Question 1 of 10

0

    What does this JavaScript code log? let x = 4; x += 5; 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.

    Code tracing: "what does this log?" explained

    Code tracing means following a program by hand to predict its output before running it. For JavaScript, track which variable each name refers to, how values change, and how operators convert types.

    Work through one statement at a time and note each variable's value after every change. Objects and arrays are shared by reference, so changing the object through one name changes what every other name that points to it sees. Strict equality === never converts types, so the string "4" and the number 4 are different. The operator + joins text when either operand is a string, while other arithmetic operators convert strings to numbers.

    const nums = [3, 1, 2];
    const copy = nums;
    copy.push(4);
    console.log(nums.length, "5" * "2", nums.indexOf("4"));
    

    Functions produce output when they are called, not where they are defined, so trace each call in the order it happens.

    Worked example

    1. nums is [3, 1, 2], and copy refers to the same array.
    2. copy.push(4) changes that shared array to [3, 1, 2, 4].
    3. nums.length is 4.
    4. "5" * "2" converts both strings to numbers, giving 10.
    5. nums.indexOf("4") uses strict equality, and the array holds the number 4, so nothing matches and the result is -1.

    The program logs 4 10 -1.

    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 = 4; x += 2; console.log(x)

    • Medium

      What does this JavaScript code log? let x = 2; x *= 6; x -= 4; console.log(x)

    • Hard

      What does this JavaScript code log? const f = (n) => n * 2 + 4; console.log(f(9) + f(8))