๐ 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);
With template literals:
const name = "Rahmeh";
const message = `Hello, ${name}! Welcome to JavaScript.`;
console.log(message);
โ 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);
With template literals:
const newWay = `Hello!
Welcome to JavaScript.
Let's learn together!`;
console.log(newWay);
โ
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.
โ 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.`);
๐ 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)