π¨ JavaScript Β· Topic 5 of 20
Strings & Template Literals β JavaScript Questions with Answers
30 practice questions on Strings & Template Literals, each with the correct answer and a clear explanation of why it is right. Read through them as revision notes, or take this topic as an interactive quiz to test yourself.
9 easy Β· 16 medium Β· 5 hard Β· Part of JavaScript: The language of the web - basics to advanced, 20 topics.
Easy questions (9)
Q1. easy
Which quote styles can create a string in JavaScript?
const a = 'hi';
const b = "hi";
const c = `hi`; // template literal
- A Single ' ', double " " and backticks ` `
- B Only double quotes
- C Only single quotes
- D Only backticks
Answer: A β Single ' ', double " " and backticks ` `
Single and double quotes are interchangeable. Backticks create template literals, which additionally support interpolation and multi-line text.
Template literalsQuotes
Q2. easy
What is the output?
const name = "Ana";
console.log(`Hello ${name}!`);
console.log(`Hello ${name}!`); // Hello Ana!
console.log("Hello ${name}!"); // literal - no interpolation
- A Hello Ana!
- B Hello ${name}!
- C Hello name!
- D SyntaxError
Answer: A β Hello Ana!
Inside backticks, ${expression} is evaluated and inserted. This is string interpolation - far more readable than "Hello " + name + "!".
Template literalsInterpolation
Q4. easy
How do you create a MULTI-LINE string most easily?
const html = `
<div>
<p>Hello</p>
</div>
`;
- A Use backticks - line breaks inside are preserved
- B Use \n in single quotes only
- C Multi-line strings are impossible
- D Use triple quotes
Answer: A β Use backticks - line breaks inside are preserved
Template literals keep real line breaks, so HTML blocks and long messages stay readable. (\n still works inside ordinary quotes.)
Template literalsMulti-line
Q5. easy
What is the output?
console.log("hello".length);
- A 5
- B 4
- C 6
- D undefined
Answer: A β 5
length is a PROPERTY (no parentheses) giving the number of characters. Note: "hello".length() would be a TypeError.
lengthProperties
Q6. easy
What is the output?
console.log("hello"[0], "hello".charAt(1));
- A h e - indexing starts at 0
- B e l
- C h h
- D undefined e
Answer: A β h e - indexing starts at 0
Both bracket notation and charAt() read a character by index, counting from 0. Bracket notation returns undefined for out-of-range; charAt returns "".
IndexingcharAt
Q8. easy
What does "hello".toUpperCase() return - and does it change the original?
let s = "hello";
s.toUpperCase(); // result discarded!
console.log(s); // "hello"
s = s.toUpperCase(); // correct
console.log(s); // "HELLO"
- A "HELLO", and the original is unchanged (strings are immutable)
- B "HELLO", and the original becomes uppercase too
- C "hello"
- D undefined
Answer: A β "HELLO", and the original is unchanged (strings are immutable)
Every string method returns a NEW string; the original can never be modified. You must capture the result: s = s.toUpperCase().
ImmutabilityString methods
Q12. easy
Which method checks whether a string CONTAINS another string?
const s = "hello world";
console.log(s.includes("world")); // true
console.log(s.startsWith("hello")); // true
console.log(s.endsWith(".js")); // false
- A includes()
- B contains()
- C has()
- D find()
Answer: A β includes()
"hello world".includes("world") returns true/false. Related: startsWith(), endsWith(), and indexOf() (which returns a position or -1).
includesindexOf
Q14. easy
What does " hi ".trim() return?
const input = " ana@mail.com ";
const clean = input.trim();
- A "hi"
- B " hi"
- C "hi "
- D "h i"
Answer: A β "hi"
trim() removes whitespace from BOTH ends (not the middle). Always trim user input from forms. trimStart() and trimEnd() handle one side.
trimInput validation
Q17. easy
How do you join two strings?
const full = first + " " + last;
const full2 = `${first} ${last}`; // preferred
- A With + or a template literal
- B With & only
- C With .concat() only
- D With ,
Answer: A β With + or a template literal
+ concatenates, and template literals are the modern readable choice. concat() exists but is rarely used.
ConcatenationTemplate literals
Medium questions (16)
Q3. medium
What can go inside ${ } in a template literal?
console.log(`Total: ${price * qty}`);
console.log(`${age >= 18 ? "adult" : "minor"}`);
console.log(`${user.name.toUpperCase()}`);
- A Any expression - variables, maths, function calls, even ternaries
- B Only variable names
- C Only strings
- D Only numbers
Answer: A β Any expression - variables, maths, function calls, even ternaries
The braces hold a full expression, evaluated and converted to a string.
Template literalsExpressions
Q7. medium
What does "hello".at(-1) return?
console.log("hello".at(-1)); // "o"
console.log("hello"[-1]); // undefined
- A "o" - at() accepts NEGATIVE indexes counting from the end
- B "h"
- C undefined
- D Error
Answer: A β "o" - at() accepts NEGATIVE indexes counting from the end
at() (ES2022) supports negative indexes, unlike bracket notation. "hello"[-1] gives undefined, but "hello".at(-1) gives the last character.
at()Negative index
Q9. medium
What happens?
let s = "hello";
s[0] = "H";
console.log(s);
- A "hello" - strings are immutable, so the assignment silently does nothing
- B "Hello"
- C TypeError
- D "H"
Answer: A β "hello" - strings are immutable, so the assignment silently does nothing
You cannot change a character in place. In non-strict mode the assignment is ignored silently; in strict mode it throws. Build a new string instead: "H" + s.slice(1).
ImmutabilityStrings
Q10. medium
What does "javascript".slice(0, 4) return?
const s = "javascript";
console.log(s.slice(0, 4)); // "java"
console.log(s.slice(4)); // "script"
console.log(s.slice(-6)); // "script" - from the end
- A "java"
- B "javas"
- C "script"
- D "jav"
Answer: A β "java"
slice(start, end) extracts from start UP TO but not including end: indexes 0,1,2,3 give "java".
slicesubstring
Q13. medium
What does "hello".indexOf("z") return?
- A -1 - the standard 'not found' result
- B 0
- C undefined
- D null
Answer: A β -1 - the standard 'not found' result
indexOf returns the first position of the substring, or -1 when absent. Older code tests 'if (s.indexOf(x) !== -1)'; modern code uses includes().
indexOfincludes
Q15. medium
What does "a,b,c".split(",") return?
"a,b,c".split(","); // ["a","b","c"]
"abc".split(""); // ["a","b","c"]
["a","b"].join("-"); // "a-b"
- A The array ["a", "b", "c"]
- B The string "abc"
- C ["a,b,c"]
- D undefined
Answer: A β The array ["a", "b", "c"]
split(separator) breaks a string into an ARRAY. split("") splits into individual characters. The reverse operation is array.join(separator).
splitjoin
Q16. medium
What does "banana".replace("a", "o") return?
"banana".replace("a", "o"); // "bonana"
"banana".replaceAll("a", "o"); // "bonono"
"banana".replace(/a/g, "o"); // "bonono"
- A "bonana" - replace() changes only the FIRST match
- B "bonono"
- C "banana"
- D "bonan"
Answer: A β "bonana" - replace() changes only the FIRST match
replace() with a string replaces one occurrence. Use replaceAll() (ES2021) or a global regex /a/g to replace every match.
replacereplaceAllRegex
Q18. medium
What is the output?
console.log("5" + 5, 5 + 5);
- A "55" 10
- B 10 10
- C "55" "55"
- D NaN 10
Answer: A β "55" 10
With a string operand, + concatenates ("55"); with two numbers it adds (10). Always convert form input with Number() before doing maths.
CoercionConcatenation
Q19. medium
What does "abc".repeat(3) return?
console.log("-".repeat(20)); // --------------------
- A "abcabcabc"
- B "abc3"
- C ["abc","abc","abc"]
- D Error
Answer: A β "abcabcabc"
repeat(n) returns the string repeated n times - useful for separators and simple patterns.
repeat
Q20. medium
What does "5".padStart(3, "0") return?
const mins = "7".padStart(2, "0"); // "07"
console.log(`10:${mins}`); // 10:07
- A "005" - pads the start until the string reaches length 3
- B "500"
- C "5"
- D "0005"
Answer: A β "005" - pads the start until the string reaches length 3
padStart/padEnd fill a string to a target length. Perfect for clock digits and invoice numbers.
padStartFormatting
Q22. medium
How do you compare two strings ignoring case?
if (input.toLowerCase() === "yes") { } // accepts YES, Yes, yes
- A Convert both with toLowerCase() then compare with ===
- B Use == which ignores case
- C Use compareIgnoreCase()
- D Strings cannot be compared
Answer: A β Convert both with toLowerCase() then compare with ===
JavaScript comparison is always case-sensitive; normalise first. (For international text, a.localeCompare(b, undefined, {sensitivity:'base'}) is more correct.)
toLowerCaseComparison
Q23. medium
What is the output?
console.log("apple" < "banana");
- A true - strings compare alphabetically by character code
- B false
- C NaN
- D Error
Answer: A β true - strings compare alphabetically by character code
Comparison walks character by character using Unicode values. Note all UPPERCASE letters come before lowercase, so "Zoo" < "apple" is true.
String comparisonUnicode
Q24. medium
How do you insert a quote inside a string?
She said "hi"
'She said "hi"';
"She said \"hi\"";
`She said "hi"`;
- A Escape it with \" or wrap the string in the other quote type
- B It is impossible
- C Use two quotes ""hi""
- D Use a comma
Answer: A β Escape it with \" or wrap the string in the other quote type
Either escape the quote with a backslash or use different outer quotes. Backticks avoid the problem entirely.
EscapingQuotes
Q25. medium
What does the escape sequence \n produce?
- A A new line
- B A literal backslash-n
- C A tab
- D Nothing
Answer: A β A new line
\n is a newline, \t a tab, \\ a literal backslash, \" an escaped quote. Inside template literals you can simply press Enter instead.
Escape sequences
Q27. medium
What does the ${} syntax do OUTSIDE backticks?
console.log("Hi ${name}");
- A Nothing special - it prints literally as Hi ${name}
- B It still interpolates
- C SyntaxError
- D It prints undefined
Answer: A β Nothing special - it prints literally as Hi ${name}
Interpolation only works inside backticks. Forgetting to switch from quotes to backticks is a very common beginner mistake.
Template literalsCommon mistakes
Q29. medium
How do you convert a number to a string?
String(42); // "42"
(42).toString(); // "42"
(255).toString(16); // "ff"
- A String(n), n.toString(), or `${n}`
- B n.toText()
- C (string) n
- D n + 0
Answer: A β String(n), n.toString(), or `${n}`
All three work. toString() also accepts a radix: (255).toString(16) gives "ff". Note String(null) works but null.toString() throws.
toStringConversion
Hard questions (5)
Q11. hard
What is the key difference between slice() and substring()?
"hello".slice(-3); // "llo"
"hello".substring(-3); // "hello" (treated as 0)
- A slice() accepts NEGATIVE indexes (counting from the end); substring() treats them as 0
- B They are identical
- C substring() is faster
- D slice() only works on arrays
Answer: A β slice() accepts NEGATIVE indexes (counting from the end); substring() treats them as 0
slice(-3) takes the last three characters; substring(-3) behaves like substring(0). substring also swaps its arguments if start > end. Prefer slice.
slicesubstring
Q21. hard
How do you REVERSE a string in JavaScript?
const s = "hello";
console.log(s.split("").reverse().join("")); // "olleh"
- A s.split("").reverse().join("") - strings have no reverse() method
- B s.reverse()
- C s[::-1]
- D reverse(s)
Answer: A β s.split("").reverse().join("") - strings have no reverse() method
reverse() is an ARRAY method, so convert to an array, reverse, and join back. ([...s].reverse().join("") also works.)
splitreversejoin
Q26. hard
What is the output?
console.log("hello".split("").map(c => c.toUpperCase()).join(""));
- A "HELLO"
- B ["H","E","L","L","O"]
- C "hello"
- D Error
Answer: A β "HELLO"
Split into characters, transform each with map, then join back into a string. (toUpperCase() alone does the same here, but this chain pattern generalises to any per-character transformation.)
Method chainingmap
Q28. hard
What is a tagged template literal?
tag`Hello ${name}`
function upper(strings, ...values) {
return strings.reduce((out, s, i) =>
out + s + (values[i] ? String(values[i]).toUpperCase() : ""), "");
}
console.log(upper`hi ${"ana"}`); // "hi ANA"
- A A function call where the function receives the string pieces and the interpolated values separately
- B An HTML tag
- C A comment style
- D Invalid syntax
Answer: A β A function call where the function receives the string pieces and the interpolated values separately
Placing a function name before a template literal calls it with (stringsArray, ...values), letting you post-process the result. Libraries use it for styled-components, escaping HTML and internationalisation.
Tagged templatesAdvanced
Q30. hard
What does "cafe\u0301".length reveal about string length?
console.log("π".length); // 2 - surrogate pair!
console.log([..."π"].length); // 1
- A length counts CODE UNITS, so combined characters and emoji can count as more than one
- B length always equals the visible characters
- C length is always 4
- D Unicode is not supported
Answer: A β length counts CODE UNITS, so combined characters and emoji can count as more than one
JavaScript strings are UTF-16 code units. Accented characters built from combining marks, and emoji (which use surrogate pairs), report a length larger than what the eye sees. [...str].length handles emoji better.
UnicodeUTF-16Emoji