Conditionals

Computer Science · JavaScript

Question 1 of 10

0

    What does this JavaScript code log? if (10 > 5) { console.log(1); } else { console.log(2); }

    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.

    Conditionals explained

    Conditionals let a program choose which code to run based on whether a condition is true. In JavaScript they are written with if, else, the ternary operator and switch.

    An if statement runs its block when its condition is true. Each else if is checked in order, and the first branch whose condition is true runs. Conditions usually compare values with === and combine them with && (and) and || (or). These operators short-circuit, so the right side runs only when it is needed.

    const score = 72;
    let grade;
    if (score >= 80) {
        grade = "A";
    } else if (score >= 60) {
        grade = "B";
    } else {
        grade = "C";
    }
    const status = score > 70 ? "pass" : "fail";
    

    Any value can be used as a condition. Falsy values are false, 0, the empty string, null, undefined and NaN; other values are truthy, including the empty array. In switch, each case should end with break, or execution falls through into the next case.

    Worked example

    With score 72, the test 72 >= 80 is false and 72 >= 60 is true, so grade is "B". The test 72 > 70 is true, so status is "pass". The output is B and pass.

    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? if (9 > 5) { console.log(1); } else { console.log(2); }

    • Medium

      What does this JavaScript code log? let x = 5 * 5 - 5; if (x > 5) { console.log(1); } else if (x > 0) { console.log(2); } else { console.log(3); }

    • Hard

      What does this JavaScript code log? let a = 3; let b = 6; a = a + b; b = a * 2 - 3; console.log((a > b || b % 3 === 0) ? a : b);