LearnFrenzy
Sign in Take a free test
JS

JavaScript Programming · Topic 10 of 25

Strings Questions and Concepts

  • 4 exercises
  • 60 questions
  • ~60 min
  • Answers explained

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");

Output

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);

Output

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);

Output

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}");

Output

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());

Output

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")));

Output

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"));

Output

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(""));

Output

[ '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.

Ready to test your Programming?

Timed online tests with instant scores and explanations.

About this section

About JavaScript Programming

Why it matters

  • JavaScript runs every web page and, with Node.js, servers, tools and APIs – it is the most used language in the world
  • Front-end, full-stack and MERN roles test JavaScript first, and many campus coding rounds allow it
  • "Predict the output" questions on hoisting, closures, this, coercion and the event loop are interview favourites
  • Modern ES6+ – let/const, arrow functions, destructuring, promises and async/await – is what companies expect from freshers

Who it is for

  • College students (B.Tech, BCA, MCA, B.Sc CS) learning web development and preparing for semester exams and viva
  • Freshers preparing for campus placements, online assessments and front-end interviews
  • Developers moving to React, Angular, Vue or Node.js who need strong core JavaScript
  • Anyone revising ES6 and asynchronous JavaScript before an interview

What every topic gives you

  • Study material in five tabs: concepts with runnable examples, coding techniques, programs, interview questions and a cheat sheet
  • Topic-wise MCQs on concepts and ES6 features
  • "Predict the output" puzzles – hoisting, coercion, closures, promises and timers
  • "Find the error" debugging: SyntaxError, ReferenceError, TypeError and silent logic bugs
  • Coding problems with solutions and real output, every one run on Node.js – run any study example in your browser

Asked in

  • Campus placements
  • TCS, Infosys, Wipro, Accenture, Cognizant tests
  • Front-end developer interviews
  • MERN / full-stack interviews
  • Online coding assessments
  • University practicals

How to use this section

  1. Read the study material of a topic and run the examples in the browser.
  2. Practise the four exercises – MCQs, output, debugging, coding problems – each marked Easy, Medium or Hard, and read every explanation.
  3. Revise with the interview questions and cheat sheet, then move to the next topic.

Search LearnFrenzy

Esc

Quick links