Free lesson · JavaScript Basic to Advance
Strings and Template Literals
What Is a String?
A string is text. Anything you can type — letters, numbers, punctuation, spaces, emoji — can live inside a string. In JavaScript, you create a string by wrapping characters in quotes.
const greeting = "Hello, world!";
const name = 'Olena';
const message = `I'm learning JavaScript`;
console.log(greeting);
console.log(name);
console.log(message);
Three different quote styles, three valid strings. JavaScript treats single quotes and double quotes identically — they exist purely so you can choose whichever doesn't conflict with the text inside. The third style, backticks, is special. It enables a feature called template literals, which we'll cover in detail below.
Why JavaScript Has Three Quote Styles
When you're writing text that contains an apostrophe, double quotes are convenient:
const sentence = "I'm a self-taught engineer";
console.log(sentence);
When you're writing text that contains double quotes, single quotes are convenient:
const quote = 'She said "JavaScript is weird" and walked away';
console.log(quote);
When you're writing text that contains both, or text that spans multiple lines, or text that needs to embed variables, backticks are the answer:
const name = "Olena";
const role = "Head of Product";
const bio = `${name} is the ${role} at Microsoft.
She learned JavaScript at age 26 in Warsaw.`;
console.log(bio);
Notice three things in that last example. The string spans two lines without any special escape characters. It contains ${name} and ${role}, which are replaced with the actual values of those variables. And it reads more naturally than the equivalent old-style concatenation would.
That's a template literal. We'll come back to it.
Interactive animation: The same message built with + concatenation and with a template literal - backticks put the sentence back.
The Most Useful String Methods
Strings come with built-in methods — functions that work on the string itself. Here are the ones you'll use constantly.
const message = "Learning JavaScript at AlgoInsight";
console.log(message.length); // 33
console.log(message.toUpperCase()); // "LEARNING JAVASCRIPT AT ALGOINSIGHT"
console.log(message.toLowerCase()); // "learning javascript at algoinsight"
console.log(message.includes("JavaScript")); // true
console.log(message.startsWith("Learning")); // true
console.log(message.endsWith("AlgoInsight")); // true
console.log(message.indexOf("JavaScript")); // 9
console.log(message.slice(9, 19)); // "JavaScript"
console.log(message.replace("Learning", "Mastering")); // "Mastering JavaScript at AlgoInsight"
console.log(message.split(" ")); // ["Learning", "JavaScript", "at", "AlgoInsight"]
Notice something important here: none of these methods change the original string. message is still "Learning JavaScript at AlgoInsight" after all of those calls. Each method returns a new string. This is because strings in JavaScript are immutable — once created, they can never be modified. You can only create new strings based on the old ones.
This is different from how many beginners assume strings work. There is no message[0] = "X" that changes the first letter. You can read message[0] and get "L", but you cannot write to it. To "change" a string, you create a new one.
Interactive animation: Cleaning user input one method at a time - each method returns a new string for the next step.
Template Literals: The Modern Way to Build Strings
Before ES6 (2015), building a string that combined variables and text was painful:
const name = "Olena";
const age = 35;
// Old style — string concatenation
const oldStyle = "Hello, " + name + ". You are " + age + " years old.";
console.log(oldStyle);
Plus signs everywhere, easy to forget a space, hard to read once the string gets long. Template literals fixed all of this:
const name = "Olena";
const age = 35;
const newStyle = `Hello, ${name}. You are ${age} years old.`;
console.log(newStyle);
The ${...} syntax is called an expression placeholder. Anything inside the curly braces is evaluated and inserted into the string. You can put any JavaScript expression in there — not just variables, but math, function calls, conditionals:
const price = 19.99;
const quantity = 3;
console.log(`Total: ${(price * quantity).toFixed(2)}`);
console.log(`Plural: ${quantity > 1 ? "items" : "item"}`);
console.log(`Today is ${new Date().toDateString()}`);
Three different expressions inside three different template literals. Math, a ternary expression, and a method call — all of them work seamlessly. This is why backticks have replaced the old plus-sign style in nearly all modern JavaScript code.
graph LR
A["Template Literal<br/>` ... `"] --> B[Text portions<br/>kept as-is]
A --> C["Expression placeholders<br/>${...}"]
C --> D[Evaluated]
D --> E[Result inserted into string]
B --> F[Final string]
E --> F
style A fill:#7c3aed,color:#fff
style F fill:#10b981,color:#fff
This diagram shows how a template literal is processed. JavaScript reads the backtick-delimited string and identifies two kinds of content: text portions which are kept as-is, and expression placeholders marked with dollar-sign and curly braces. The expressions inside the placeholders are evaluated and their results are inserted into the appropriate positions, producing the final string.
Escaping Special Characters
Sometimes you need a character inside a string that would normally end it — like a quote of the same type, or a literal backslash. You handle this with an escape character, which is a backslash \.
const escaped1 = "She said \"hello\" and waved";
const escaped2 = 'It\'s a beautiful day';
const escaped3 = "First line\nSecond line";
const escaped4 = "Path: C:\\Users\\Olena";
console.log(escaped1);
console.log(escaped2);
console.log(escaped3);
console.log(escaped4);
\" produces a literal double quote inside a double-quoted string. \' does the same for single quotes. \n produces a newline (line break). \\ produces a single literal backslash. These are the four escape sequences you'll use most often.
Template literals reduce the need for some escaping — you don't need \n in a backtick string because you can just press Enter inside the string. But the principle still applies for backticks inside backticks (rare) and for other special characters.
Common Pitfalls
Interactive animation: A string method called without catching its result - the line runs and changes nothing, because strings are immutable.
Warning: Two things about strings that catch beginners off guard.
Strings are immutable. Doing
myString[0] = "X"does nothing — JavaScript silently ignores the assignment. To "change" a string, you must build a new one. Beginners coming from languages like Python or C often expect to modify strings in place. You can't.
"5" + 3is not what you might expect. Because the+operator works on both numbers (addition) and strings (concatenation), JavaScript has to decide which one to do. When either side of+is a string, it does concatenation — and converts the other side to a string first. So"5" + 3produces"53", not8. This is one of JavaScript's most-cited quirks and we'll return to it in Topic 2.6 on type coercion.
Why This Matters in Interviews
Interview: String manipulation is a common interview topic. Many DSA problems are framed around strings — reverse a string, check if it's a palindrome, find the first non-repeating character. Fluency with the string methods listed above (
slice,indexOf,split,includes,replace) lets you write clean solutions without hand-rolling logic for things JavaScript already provides.Topic 2.8 — Interview Lens: Type Coercion Questions — covers the string-meets-number coercion patterns that show up in interview puzzles.
Try It
Exercise: Given a string
const sentence = "The quick brown fox jumps over the lazy dog", use string methods to produce each of these results:
- The length of the sentence
- The sentence in all uppercase
- The position of the word "fox"
- The sentence with "fox" replaced by "cat"
- An array of all the words
- A new string using a template literal that says:
"The sentence has X characters and Y words"(with X and Y as the actual numbers)Each one is solvable with a single method call or expression. If you find yourself writing a loop, there's a built-in method that does what you need.