DEV Community

Rahma Sameh
Rahma Sameh

Posted on

Day 1: Mastering JavaScript Template Literals

๐Ÿš€ Welcome to Day 1 of my 100-day web development challenge!

Today, weโ€™re diving into template literalsโ€”one of JavaScriptโ€™s most useful features for handling strings dynamically.

What Are Template Literals?

Template literals are a modern way to work with strings in JavaScript. Unlike regular strings, they:

โœ… Use backticks () instead of quotes ("" or '').

โœ… Support multi-line strings without needing \n.

โœ… Allow embedded expressions using ${} (known as string interpolation).

Why Are They Useful?

1๏ธโƒฃ Easier String Concatenation
Before template literals:

const name = "Rahmeh";
const message = "Hello, " + name + "! Welcome to JavaScript.";
console.log(message);
Enter fullscreen mode Exit fullscreen mode

With template literals:

const name = "Rahmeh";
const message = `Hello, ${name}! Welcome to JavaScript.`;
console.log(message);
Enter fullscreen mode Exit fullscreen mode

โœ… Cleaner and more readable!

2๏ธโƒฃ Multi-Line Strings Without \n
Before:

const oldWay = "Hello!\nWelcome to JavaScript.\n Let's learn together!";
console.log(oldWay);
Enter fullscreen mode Exit fullscreen mode

With template literals:

const newWay = `Hello!
Welcome to JavaScript.
Let's learn together!`;
console.log(newWay);
Enter fullscreen mode Exit fullscreen mode

โœ… No need for \n or string concatenation!

3๏ธโƒฃ Expression Evaluation Inside Strings

const a = 10;
const b = 5;
console.log(`The sum of ${a} and ${b} is ${a + b}.`); 
// Output: The sum of 10 and 5 is 15.
Enter fullscreen mode Exit fullscreen mode

โœ… Perform calculations and insert values dynamically.

๐Ÿš€ Challenge of the Day:
Now that we understand template literals, let's apply them!

๐Ÿ’ก Challenge: Write a program that:

๐Ÿ”น Asks the user for their name and age.

๐Ÿ”น Calculates how many years until they turn 100.

๐Ÿ”น Displays a friendly message using template literals.

Example Output:

Hello, Rahmeh! You are 25 years old. You will turn 100 in 75 years.

Starter Code:

const name = prompt("What is your name?");
const age = prompt("How old are you?");
const yearsTo100 = 100 - age;

console.log(`Hello, ${name}! You are ${age} years old. You will turn 100 in ${yearsTo100} years.`);
Enter fullscreen mode Exit fullscreen mode

๐Ÿ“ Whatโ€™s Next?

โœ… Try modifying the program to handle invalid inputs.

โœ… Add a simple HTML form instead of prompt().

โœ… Experiment with multi-line template literals.

Stay tuned for Day 2, where we explore javaScript conditionals and make this program even smarter!

๐Ÿ’ฌ Whatโ€™s your favorite use case for template literals?
Drop a comment! ๐Ÿš€

Top comments (0)