Template literals
หน้านี้ต้องใช้เบราว์เซอร์ล่าสุด (รองรับ SharedArrayBuffer) กรุณาอัปเดต Chrome, Edge, Firefox หรือ Safari เป็นเวอร์ชันล่าสุด
English
A cleaner way to build strings
- Wrap a string in backticks
`and you can drop values straight in with${...}. - This is a template literal — much tidier than joining with lots of
+.

English
let name = "Ada";
let age = 15;
console.log(`${name} is ${age}`); // → Ada is 15
English
Any expression fits inside ${ }
- Whatever you write inside
${...}is worked out first, then dropped into the string.
English
let a = 3;
let b = 4;
console.log(`${a} + ${b} = ${a + b}`); // → 3 + 4 = 7
English
Same string, two ways
+and a template literal can build exactly the same text.- In backticks, spaces and punctuation stay where you type them, so a missing space is easy to see.
English
let item = "pen";
let price = 3;
console.log("A " + item + " costs " + price + " yuan."); // → A pen costs 3 yuan.
console.log(`A ${item} costs ${price} yuan.`); // → A pen costs 3 yuan.
English
Watch out
- Backticks
`are not the same as quotes'or".${...}only works inside backticks. - Bonus: a backtick string can span several lines — handy for longer messages.
English
Common mistakes
- Template literals use backticks and
${...}:`Hi ${name}`, not quotes. - Inside
${...}you can put any expression.
English
Now you try
- Use backticks and
${...}. - Press Check answer to test it.
ความยาก 1/5 · 100 เหรียญ + บอนัสน้อยๆ เมื่อทำสำเร็จครั้งแรกในวันนี้
let name = "Sam". Use a template literal (backticks) to log Hello, Sam!.
คลิก Run เพื่อดูผลลัพธ์ที่นี่
ความยาก 1/5 · 100 เหรียญ + บอนัสน้อยๆ เมื่อทำสำเร็จครั้งแรกในวันนี้
a เป็น 3 และ b เป็น 4. Use a template literal to log 3 + 4 = 7 (put a + b inside ${ }).
คลิก Run เพื่อดูผลลัพธ์ที่นี่
ความยาก 1/5 · 100 เหรียญ + บอนัสน้อยๆ เมื่อทำสำเร็จครั้งแรกในวันนี้
Use a template literal to log Total: 10, working out the 10 as 5 * 2 inside ${ }.
คลิก Run เพื่อดูผลลัพธ์ที่นี่