JavaScriptLesson 4 of 16
Strings and template literals
Almost everything a program shows to a person is a string. JavaScript strings come with plenty of ready-made methods, and template literals in backticks mix text and values without a pile of pluses.
Key points
- length is the size of a string, word[0] the first character, word.at(-1) the last
- toUpperCase() and toLowerCase() change case, trim() removes spaces at both ends
- slice(0, 3) cuts out a piece, includes("…") checks whether some text is inside
- A template literal: `Hi, ${name}!`, where ${} can hold any expression
- Methods never change the original string; they return a new one
Example
const word = "JavaScript";console.log(word.length);console.log(word.toUpperCase(), word[0], word.at(-1));console.log(word.slice(0, 4), word.includes("Script"));console.log(" hi ".trim() + "!"); const user = "Lea";console.log(`Hi, ${user}! 2 + 3 = ${2 + 3}`);Methods can be chained: trim first, then toUpperCase. Inside a template literal, ${2 + 3} is worked out first and then inserted.
Task
How to use the editor⌘ Enter or Ctrl Enter runs the code, ⇧ ⌘ Enter checks the task.Tab and Shift Tab indent the line or the selection; Esc, then Tab leaves the editor.The check compares what the program printed with the task; spaces at line ends do not matter.After two failed checks you may open the solution. Your code is kept in this browser.A coffee shop prints an order ticket. Clean up the name (no spaces around it, in capitals), build the pickup code from the first three letters of the drink in capitals, a dash and the length of the name, and print three lines: Order for SAM: flat white, Total: 4.50 USD and Pickup code: FLA-3.
Output
What your program prints appears here.