CodeStride
Getting Started

Text (strings) in JavaScript

Topic 4 of 64 · 9 minFree lesson

A string is a piece of text. It can hold letters, spaces, digits and symbols. Names, messages and passwords are all strings, so you'll use them in almost every program.

Double or single quotes

You make a string by putting text inside quotes. Double quotes " and single quotes ' work the same way. Pick one style and stick with it.

Example 1
const greeting = "Hello";const language = 'JavaScript';console.log(greeting);console.log(language);
HelloJavaScript

If your text has an apostrophe in it, wrap it in double quotes. Then JavaScript knows the apostrophe is part of the text, not the end of it.

Example 2
console.log("It's sunny today.");
It's sunny today.

Joining strings

Use + to join strings together. This is called concatenation. JavaScript won't add spaces for you, so put them in yourself.

Example 3
const first = "Ada";const last = "Lovelace";console.log(first + " " + last);
Ada Lovelace

How long is it?

Every string knows how many characters it has. Write .length after it to find out. Spaces and punctuation count too.

Example 4
const city = "Lisbon";console.log(city.length);console.log("Hi there!".length);
69

Special characters

Some characters are hard to type inside a string. A backslash \ starts an escape character: a short code for one of them. \n starts a new line, and \" puts a double quote inside double quotes.

Example 5
console.log("Line one\nLine two");console.log("She said \"hi\" and waved.");
Line oneLine twoShe said "hi" and waved.

\n is two characters in your code, but JavaScript treats it as one line break.

Strings can't be changed

Each character has a position number called an index. Counting starts at 0, so word[0] is the first character. You can read a character this way, but you can't change it.

Example 6
const word = "Java";console.log(word[0]);word[0] = "L";
JTypeError: Cannot assign to read only property '0' of string 'Java'

Once a string is made, it never changes. To get different text, make a new string, for example with +. You'll meet lots of ways to build new strings in later topics.

Common mistakeMixing up a number and digits in quotes. 5 is a number, but "5" is text. When one side of + is a string, JavaScript joins instead of adding.
Example 7
console.log(5 + 5);console.log("5" + 5);
1055
TipWhen you need to show text and a number together, a comma in console.log() is often clearest: console.log("Age:", 30). In the next topic, you'll learn template literals, the neatest way to mix text and values.

Try it yourself

Run the code in the editor and answer 8 practice questions on text (strings). It's free, you only need an account.