Template Literals
Part of the Logic & Flow section of Coddy's JavaScript journey — lesson 3 of 65.
Template literals use backticks `` to create strings and allow you to insert expressions using ${}. For instance, when creating greetings, you can dynamically embed names or other data directly into the template literal.
Example:
const userName = "Sam";
const message = `Welcome, ${userName}!`;
// Inserts userName inside the stringTemplate literals also support multi-line strings without needing the \n escape character. You can simply press Enter for a new line, and the line break will be preserved in the output. Both approaches work:
// Using \n
const message1 = `Line 1\nLine 2`;
// Using actual line breaks
const message2 = `Line 1
Line 2`;Both produce the same result
Challenge
EasyCreate a function named greetAll that takes an array of names and returns one string. Each name in the array should produce a line with the format Hello, <Name>! joined together into a single string, separated by newlines. Use template literals for the greeting lines.
Cheat sheet
Template literals use backticks `` to create strings and allow you to insert expressions using ${}:
const userName = "Sam";
const message = `Welcome, ${userName}!`;
// Inserts userName inside the stringTemplate literals support multi-line strings without needing \n escape characters:
// Using \n
const message1 = `Line 1\nLine 2`;
// Using actual line breaks
const message2 = `Line 1
Line 2`;
// Both produce the same resultTry it yourself
function greetAll(names) {
// Write your code here
}
// Do not write anything outside functionThis lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Logic & Flow
1Strings In Depth
String FundamentalsIterate Over StringsTemplate LiteralsString MethodsRecap - String Weaver4JSON Part 2
Iterate Over JSONNested JSONJSON Optional ChainingShallow And Deep CopyRecap - Bicycle ShopRecap - Solar System10Manage Festival System
Project OverviewAdd Movies & Venues2Multi-dimensional Arrays
2D Arrays BasicsAccessing 2D Array ElementsNested Loops with 2D ArraysRecap - 2D ArraysMatrix Addition & SubstractionJagged Arrays3D Arrays And BeyondCommon 2D Array PatternsRecap - All About Arrays5Sets Part 1
What Is A Set?Iterating Over SetsAdding An ElementRemoving An ElementChecking If An Element ExistsSize And Is EmptyCopy And ClearRecap - Basic Of Sets8Arrays Interesting Topics
Array DestructuringSpread Syntax in ArraysSparse ArraysRecap - Arrays Workshop3JSON Part 1
What is a JSON?Check If Key ExistsObject MethodsThe Spread Operator Part 1The Spread Operator Part 2Remove KeysRecap - JSON Manipulate Keys