Introduction and Lesson Goal

Greetings, friend of code! We're going to delve into JavaScript's string formatting and interpolation, transforming static text into dynamic messages using JavaScript's Template Literals — a very helpful strings management feature. By the end of this lesson, you'll be adept at formatting and navigating text strings, akin to a seasoned JavaScript astronaut.

Understanding String Formatting

String formatting enables us to shape dynamic messages in programming. Imagine an app displaying a personalized message like, "Good morning, Sam! The current temperature is 70 degrees." Now, let's assemble various elements in JavaScript:

JavaScript
let name = "Sam";
let temperature = 70;
let weatherMessage = "Good morning, " + name + "! The current temperature is " + temperature + " degrees.";
console.log(weatherMessage); // Prints: Good morning, Sam! The current temperature is 70 degrees.
Exploring Template Literals

JavaScript's Template Literals offer a superior approach for string formatting. Enclosed within backticks (`), they smoothly accommodate variables or expressions inside ${}:

JavaScript
let name = "Sam";
let temperature = 70;
// Note that for string literals, we use backticks, not single or double quotes
let weatherMessage = `Good morning, ${name}! The current temperature is ${temperature} degrees.`;
console.log(weatherMessage); // Prints: Good morning, Sam! The current temperature is 70 degrees.

The output, identical to our previous approach, achieves the same goal but with enhanced readability.

Comparing Concatenation to Template Literals
Sign up
Join the 1M+ learners on CodeSignal
Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal