Reading — step 1 of 5
Learn
Template Literals
You already know how to build a string out of pieces with +:
It works, but look at it: quote, text, quote, plus, variable, plus, quote... Every boundary is a chance to drop a space or a punctuation mark, and each added variable makes it worse. To read it, you have to mentally re-assemble the sentence.
Template literals fix this. Wrap the string in backticks (`) instead of quotes, and embed values directly inside it with ${...}:
The string reads like the final sentence, and each value sits exactly where it will appear in the output. This is the default way to build strings in modern JavaScript — fall back to + only for trivial cases.
The trap: backticks, not quotes
The number-one beginner mistake with template literals: writing ${...} inside NORMAL quotes. Interpolation only happens inside backticks:
Single and double quotes treat ${name} as plain text. If your output literally contains a dollar sign and curly braces, this is why. On most keyboards the backtick key sits at the top-left, under Esc — it is not the single-quote key.
Anything inside ${...} is an expression
You are not limited to variable names. Any JavaScript expression works — arithmetic, function calls, even ternaries:
Keep the expressions short, though. A template literal stuffed with logic is harder to read than the + version it replaced.
Multi-line strings
Backticks also allow real line breaks inside the string — no \n escapes required:
With normal quotes a literal line break is a syntax error; you would need "line one\nline two". Both work — the backtick version simply shows the shape of the output directly in the code.
Numbers interpolate cleanly
${...} converts values to text automatically. ${age} produces the same characters whether age holds the number 25 or the string "25". That matters here because everything read from input arrives as a string — and for printing, that is perfectly fine.
Your exercise
The starter reads a name (first line of input) and an age (second line) for you. Print exactly:
Hi, {name}! You are {age} years old.
So for input Alice and 25:
Hi, Alice! You are 25 years old.
Build it as ONE template literal — `Hi, ${name}! You are ${age} years old.` inside a console.log. The grader will catch the classic mistakes: using quotes instead of backticks (your output will literally contain ${name}), putting a period after the name instead of the exclamation mark — it is Hi, Alice!, not Hi, Alice. — and dropping the final period after old. Match the punctuation exactly: comma after Hi, ! right after the name, . at the very end.
Discussion
Ask a question, share an insight, or help someone who’s stuck.
Sign in to post a comment or reply.
Loading…