Text (strings) in JavaScript
Topic 4 of 64 · 9 minFree lessonA 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.
const greeting = "Hello";const language = 'JavaScript';console.log(greeting);console.log(language);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.
console.log("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.
const first = "Ada";const last = "Lovelace";console.log(first + " " + last);How long is it?
Every string knows how many characters it has. Write .length after it to find out. Spaces and punctuation count too.
const city = "Lisbon";console.log(city.length);console.log("Hi there!".length);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.
console.log("Line one\nLine two");console.log("She 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.
const word = "Java";console.log(word[0]);word[0] = "L";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.
5 is a number, but "5" is text. When one side of + is a string, JavaScript joins instead of adding.console.log(5 + 5);console.log("5" + 5);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.