edubun 한국어

Strings and template literals

"5" + 3 gives "53", not 8. When one side of + is a string, JavaScript joins text instead of adding numbers.

Text in a program

Names, messages, addresses, passwords and whole web pages are all text, and JavaScript stores text as strings. A string is a sequence of characters between quotes. JavaScript accepts three kinds of quotes: double quotes "like this", single quotes 'like this', and backticks `like this`. The first two behave the same. Backticks make a template literal, which has extra powers covered below.

If your text contains one kind of quote, wrap it in the other: "It's late" works because the apostrophe is not a double quote. You can also put a backslash before a quote to say "this one is part of the text": 'It\'s late'. A backslash followed by n, written \n, means a line break inside the string.

Length and positions

Every string knows how many characters it has: "JavaScript".length is 10. Each character also has a position, called its index, and counting starts at 0, not 1. So in "JavaScript", index 0 is J, index 4 is S and the last index is 9, one less than the length. You read a single character with square brackets: word[0]. Starting from 0 feels odd at first, but most programming languages count this way, and you will see it again with arrays.

const word = "JavaScript";
console.log(word.length);                // 10
console.log(word[0]);                    // J
console.log(word[word.length - 1]);      // t

Useful string methods

Strings come with built-in tools called methods, which you call with a dot after the string. toUpperCase() and toLowerCase() return a copy in capitals or small letters. includes("Script") answers true or false depending on whether the text appears inside. slice(0, 4) returns the characters from index 0 up to, but not including, index 4, which in "JavaScript" is "Java". trim() removes spaces from both ends, handy for cleaning up something a person typed. None of these change the original string. Strings in JavaScript cannot be changed in place; methods always hand back a new string.

Joining strings with +

The + operator joins strings end to end, which is called concatenation. "Hello, " + "Mina" gives "Hello, Mina". Spaces are not added for you, so put them inside the quotes yourself. Here is the trap from the lead: if either side of + is a string, JavaScript turns the other side into a string and joins them. "5" + 3 is "53". The other arithmetic operators do not join text, so "5" * 2 converts "5" to a number and gives 10. To turn a string that holds digits into a real number, use Number("5").

Template literals

Building a sentence with + gets messy fast: name + " is " + age + " years old." needs careful spaces and quotes. A template literal, written with backticks, lets you drop values straight into the text with ${ }. Whatever is inside the braces is evaluated as an expression and the result is placed into the string. Template literals can also span several lines.

const name = "Mina";
const age = 14;
console.log(`${name} is ${age} years old.`);   // Mina is 14 years old.
console.log(`Next year: ${age + 1}`);           // Next year: 15

Worked example. A shop label needs to read "3 apples cost 4.5". With const n = 3, price = 1.5; the template `${n} apples cost ${n * price}` does it in one line, and the multiplication happens inside the braces.

Backticks around the text, dollar sign and braces around each value: `Hi ${name}`

stringText between quotes or backticks
indexPosition of a character, counting from 0
.lengthHow many characters a string has
concatenationJoining strings with +
template literalA backtick string with ${ } placeholders
methodA tool called with a dot: word.toUpperCase()
slice(a, b)Characters from index a up to, not including, b
escape \nA line break inside a string
  1. What does this print?
    console.log("5" + 3);
  2. What does this print?
    console.log("5" * 3);
  3. What does this print?
    console.log("cat".length);
  4. What does this print?
    const s = "Seoul";
    console.log(s[1]);
  5. What does this print?
    console.log("JavaScript".slice(4, 10));
  6. What does this print?
    const a = 2;
    const b = 3;
    console.log(`${a} + ${b} = ${a + b}`);
    • 2 + 3 = 5
    • ${a} + ${b} = ${a + b}
    • 2 + 3 = 23
  7. What does this print?
    console.log("Hi" + " " + "there".toUpperCase());
  8. What does this print?
    console.log("banana".includes("nan"));
    • true
    • false
  9. What does this print?
    console.log(1 + 2 + "3");
  10. What does this print?
    console.log(Number("7") + 1);
  11. What is the last index of a string with length 6?
Key points
  • Strings use "double", 'single' or `backtick` quotes.
  • Indexes start at 0; the last index is length - 1.
  • Methods like toUpperCase, includes, slice and trim return new strings.
  • If either side of + is a string, + joins text.
  • Template literals: `text ${expression} text`.