Building Your Learning Module...
Getting things ready for you!
Find videos you like?
Save to resource drawer for future reference!
Template literals use backticks (`) instead of quotes. They allow string interpolation with ${}, multi-line strings without \n, and even tagged templates for advanced processing!
`...` instead of single/double quotes. Everything inside can span multiple lines and embed expressions!const name = 'Alice'; const age = 25; // Messy concatenation const message = 'Hello, ' + name + '! You are ' + age + ' years old.'; console.log(message); // Hello, Alice! You are 25 years old. // Gets worse with more variables const greeting = 'Welcome ' + name + ', you have ' + (10 - age) + ' years until retirement!';
const name = 'Alice';
const age = 25;
// Clean interpolation
const message = `Hello, ${name}! You are ${age} years old.`;
console.log(message);
// Hello, Alice! You are 25 years old.
// Easy to read with expressions
const greeting = `Welcome ${name}, you have ${65 - age} years until retirement!`;Embed any expression inside ${'{}'}
// Using \n for newlines const poem = 'Roses are red,\n' + 'Violets are blue,\n' + 'JavaScript is awesome,\n' + 'And so are you!'; // HTML with concatenation const html = '<div>\n' + ' <h1>Title</h1>\n' + ' <p>Content</p>\n' + '</div>';
// Natural line breaks const poem = `Roses are red, Violets are blue, JavaScript is awesome, And so are you!`; // HTML as written const html = `<div> <h1>Title</h1> <p>Content</p> </div>`;
Write strings exactly as they should appear
// Conditional (ternary)
const age = 20;
const message = `You are ${age >= 18 ? 'an adult' : 'a minor'}`;
// Array methods
const names = ['Alice', 'Bob', 'Charlie'];
const list = `Users: ${names.join(', ')}`;
// Math
const price = 99.99;
const quantity = 3;
const total = `Total: $${(price * quantity).toFixed(2)}`;
// Nested templates
const items = ['apple', 'banana'];
const html = `
<ul>
${items.map(item => `<li>${item}</li>`).join('')}
</ul>
`;
// Method calls
const text = 'hello';
console.log(`Uppercase: ${text.toUpperCase()}`);
// Uppercase: HELLOComplex expressions in template literals
Custom processing of template literals
Building HTML with template literals
Template literals use backticks `...` instead of quotes
Found on the key with tilde (~) on US keyboards
Embed any expression: variables, calculations, function calls, ternary operators
No need for \n or + concatenation
Just press Enter and keep typing!
Advanced: Custom processing functions
Used by libraries like styled-components