Introduction & Syntax
Strings · Study material
Strings hold every piece of text a program touches – names, messages, URLs, HTML, JSON. In JavaScript they are immutable primitives written with single quotes, double quotes or backticks, and most interview questions about them come down to a few facts: only template literals interpolate, string methods return new strings, length counts UTF-16 units (so an emoji counts as 2), < compares character codes (so "Zebra" < "apple"), and slice and substring treat negative numbers differently. This topic covers the core of working with strings; the String Methods topic goes deeper into searching, replacing and formatting. Then test yourself with 60 practice questions – 15 MCQs, 20 predict-the-output puzzles, 15 debugging questions and 10 coding problems – every one run on Node.js.
Quotes and escape sequences
'Single' and "double" quotes are identical; pick one style and escape the delimiter inside the string with a backslash. Backticks start a template literal. Common escapes: \n new line, \t tab, \\ backslash, \' and \" quotes, \u20B9 or \u{1F600} a Unicode character. A normal string cannot contain a raw line break.
const single = 'It\'s fine'; // escape the quote that delimits the string
const double = "She said \"hi\"";
const backtick = `Both ' and " work here`;
console.log(single, "|", double, "|", backtick);
// \n new line, \\ backslash, \u20B9 a Unicode character (₹)
console.log("\u20B9500", "Line1\nLine2".length, "C:\\temp");
It's fine | She said "hi" | Both ' and " work here ₹500 11 C:\temp
Template literals
Backtick strings evaluate ${expression} – any expression, including function calls, ternaries and nested templates – and keep line breaks exactly as written, which makes them ideal for messages and HTML snippets.
const item = "Laptop", price = 54999, qty = 2;
// ${ } can hold any expression: arithmetic, method calls, ternaries
console.log(`${item} x${qty} = ₹${(price * qty).toLocaleString("en-IN")}`);
console.log(`Stock: ${qty > 0 ? "available" : "sold out"}`);
// multi-line text and nested templates
const html = `<ul>
${["JS", "CSS"].map((t) => `<li>${t}</li>`).join("")}
</ul>`;
console.log(html);
Laptop x2 = ₹1,09,998 Stock: available <ul> <li>JS</li><li>CSS</li> </ul>
Indexing and immutability
Characters are read with str[i], str.charAt(i) or str.at(i) (negative indexes count from the end). Out of range, [] and at() give undefined while charAt() gives an empty string. Strings are immutable: assigning to str[0] does nothing (a TypeError in strict mode), and every method returns a new string that you must store.
const word = "JavaScript";
console.log(word[0], word.charAt(4), word.at(-1), word[20], word.charAt(20) === "");
const upper = word.toUpperCase(); // strings never change – methods return new strings
console.log(word, upper);
J S t undefined true JavaScript JAVASCRIPT
length and Unicode
JavaScript strings are sequences of UTF-16 code units. Most characters use one unit, but emoji and many symbols use two (a surrogate pair), so "👋".length is 2. To work with visible characters, iterate by code point: [...str], for…of, codePointAt and String.fromCodePoint.
// length counts UTF-16 code units: an emoji outside the basic plane takes two
const s = "h\u00e9llo \u{1F44B}"; // "héllo 👋"
console.log(s.length, [...s].length); // spreading iterates by code point
console.log(s.charCodeAt(0), s.codePointAt(6), String.fromCodePoint(128075) === "\u{1F44B}");
8 7 104 128075 true
Comparing strings
=== compares exactly, including case. < and > compare code unit by code unit, so all capital letters sort before lower-case ones and "10" comes before "9". For human ordering use localeCompare (which returns a negative number, 0 or a positive number) and normalise case with toLowerCase() for case-insensitive checks.
// < and > compare UTF-16 code units: all capitals come before all lower-case letters
console.log("apple" < "banana", "Zebra" < "apple", "a" < "B");
// localeCompare compares the way people expect (and can ignore accents and case)
console.log("a".localeCompare("B"), "r\u00e9sum\u00e9".localeCompare("resume", "en", { sensitivity: "base" }));
console.log("JS" === "JS", "js" === "JS", "js".toLowerCase() === "JS".toLowerCase());
true true false -1 0 true false true
Converting and concatenating
+ concatenates as soon as one operand is a string, evaluated left to right. String(x) converts any value, including null and undefined (which have no toString method). Objects become "[object Object]" and arrays become their elements joined with commas. Template literals are usually the clearest way to build text.
// + with a string concatenates; left to right
console.log("5" + 5, 5 + 5 + "5", `${5 + 5}5`);
// String() converts anything (even null); objects use their toString()
console.log(String(null), [1, 2] + "", ({}) + "", String(Symbol("id")));
55 105 105 null 1,2 [object Object] Symbol(id)
Extracting and searching
slice(start, end) and substring(start, end) both exclude end. slice understands negative indexes; substring treats negatives as 0 and swaps its arguments if start > end. indexOf returns a position or -1; includes, startsWith and endsWith return booleans. All of them are case-sensitive.
const url = "https://learnfrenzy.com/programming";
// slice accepts negative indexes; substring swaps its arguments and treats negatives as 0
console.log(url.slice(8, 23), url.substring(23, 8), url.slice(-11), url.substring(-3, 5));
console.log(url.indexOf("/", 8), url.includes("frenzy"), url.startsWith("https"), url.endsWith(".com"));
learnfrenzy.com learnfrenzy.com programming https 23 true true false
split, join, trim and repeat
split(separator) turns a string into an array and join(separator) turns it back. trim, trimStart and trimEnd remove whitespace; repeat(n) repeats a string.
const csv = " Asha, Ravi ,Meera ";
const names = csv.trim().split(",").map((n) => n.trim());
console.log(names, names.join(" & "));
console.log("ab".repeat(3), "-".repeat(10), "Hello".split(""));
[ 'Asha', 'Ravi', 'Meera' ] Asha & Ravi & Meera ababab ---------- [ 'H', 'e', 'l', 'l', 'o' ]
Common mistakes
- Calling a method without storing the result – msg.toUpperCase() alone changes nothing.
- ${ } inside quotes – only backticks interpolate.
- Comparing user input without trim/toLowerCase – "Yes " !== "yes".
- Comparing numbers stored as strings – "10" < "9" is true.
- Using length for visible characters – emoji count twice.
- str.reverse() – strings have no reverse; use [...str].reverse().join("").
- Methods on null/undefined – check optional values first (value?.trim()).
Key points to remember
- Strings are immutable primitives; methods return new strings.
- Only template literals interpolate and span lines.
- Out of range: str[i] and at() give undefined, charAt() gives "".
- length counts UTF-16 units; [...str] counts code points.
- < compares code units; localeCompare compares like a dictionary.
- slice allows negative indexes; substring does not.
- String(x) is the safe way to convert any value.
Frequently asked questions
Single quotes, double quotes or backticks?
Functionally single and double quotes are the same; follow your project's style guide (Prettier defaults to double). Use backticks whenever you insert values or need several lines.
Is building strings with + in a loop slow?
Modern engines optimise concatenation well. For very large outputs, pushing parts into an array and calling join once is still a clean, predictable approach.
How do I compare strings ignoring case and accents?
a.localeCompare(b, undefined, { sensitivity: "base" }) === 0, or compare a.toLowerCase() with b.toLowerCase() when accents do not matter.
Where can I learn more?
Read JavaScript String Methods and Template Literals in the JavaScript tutorial, then practise with the exercises below.