JavaScript by Example

Strings

A string is text. JavaScript has several ways to create and combine strings, with template literals being the most flexible option.

A string is text. Write one between single quotes, double quotes, or backticks. These classic operations cover the things beginners do most often: join text, inspect its length, change its case, and take a piece of it.

The + operator joins strings. Strings also provide properties and methods for common text operations. Positions start at zero, so slice(0, 5) takes the first five characters. Backticks create a template literal. Inside one, ${name} inserts the value of name into the text.

const first = "Hello";
const second = "world";
console.log(first + ", " + second + "!"); // Hello, world!
 
const message = "JavaScript is fun";
console.log(message.length);         // 17
console.log(message.toUpperCase());  // JAVASCRIPT IS FUN
console.log(message.includes("fun")); // true
console.log(message.slice(0, 10));   // JavaScript
 
const name = "Mina";
console.log(`Welcome, ${name}!`); // Welcome, Mina!

In production

Strings cannot be changed in place. Methods such as toUpperCase() return a new string, so store the result when you need it later. Prefer template literals when text includes values because they stay readable as the message grows.

Enjoyed this? Get more software craft delivered to your inbox.