Strings & template literals

Computer Science · JavaScript

Question 1 of 10

0

    What does this JavaScript code log? const s = `oceancat`; console.log(s.length);

    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.

    Strings & template literals explained

    Strings hold text in JavaScript. Template literals, written with backticks, are a convenient way to build them: they can span several lines, and they can insert the value of an expression into the text.

    Single and double quotes behave the same and must be closed with the same quote. Backticks create a template literal. An expression placed inside a dollar sign followed by curly braces is evaluated, converted to text and inserted into the string.

    const poem = `Roses are red
    violets are blue`;
    console.log(poem.length);
    console.log("hello".slice(1, 4));
    

    Strings are immutable. Methods such as toUpperCase, slice and replace return a new string, so the result must be stored. slice(start, end) stops before end. length counts UTF-16 code units, so some emoji report a length larger than the number of characters a reader sees.

    Worked example

    The text "Roses are red" has 13 characters, the newline inside the template adds 1, and "violets are blue" has 16, so poem.length is 30. The slice from index 1 up to index 4 takes the characters at positions 1, 2 and 3 of hello, giving ell. Output: 30, then ell.

    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?

      const s = lambdajson; console.log(s.length);

    • Medium

      What does this JavaScript code log?

      const w = "code"; console.log(${w.slice(1, 2)}|${w.length}.length);

    • Hard

      What does this JavaScript code log?

      const a = "template"; const b = "json"; console.log(${a}\t${b}.length);