Show pageOld revisionsBacklinksFold/unfold allBack to top This page is read only. You can view the source, but not change it. Ask your administrator if you think this is wrong. ====== Javascript ====== ===== Template literals ===== Template literals are syntaxed ''${...}'' In JavaScript, strings can be written in three ways: <code javascript> 'string' // single quotes "string" // double quotes `string` // backticks → template literal </code> Only template literals (backticks) support interpolation using: ''${expression}'' Inside ''${...}'', you can put any valid JavaScript expression: * variables * function calls * arithmetic * ternaries * property access === Examples === <code javascript> const name = 'Alex'; `Hello ${name}!`; </code> This produces: <code text> Hello Alex! </code> Template literals can be very useful to replace long lists of 'string' + var + 'string' + var ... <code javascript> 'Tag: ' + tag_autospawn + ' - Spawned car ' + suffix </code> This works, but: * It’s visually noisy * Easy to miss a space * Harder to refactor * Encourages line-breaking when long The template literal equivalent is: <code javascript> `Tag: ${tag_autospawn} - Spawned car ${suffix}` </code> Same result, much clearer structure. A template literal is: * One string * With embedded expressions * Much easier to keep visually compact So this: '''foo ' + a + ' bar ' + b + ' baz ' + c'' Becomes: ''`foo ${a} bar ${b} baz ${c}`'' ==== Not limited to variables ==== Inside ''${}'', you can do more: <code javascript> `UV: ${car_uv.toFixed(2)}` `State: ${isActive ? 'ON' : 'OFF'}` `Next index: ${pointer + 1}` </code> This is real code, not just substitution. ==== Runtime behavior (important) ==== Template literals: * Are evaluated at runtime * Produce a normal string * Have no performance penalty compared to concatenation in modern JS engines * Are fully supported in ES6+ (basically everything now) So: '''Hello ' + name'' and: ''`Hello ${name}`'' Compile down to equivalent bytecode in modern engines. ==== Multiline strings (bonus) ==== Template literals also preserve newlines exactly as written: <code javascript> `Line 1 Line 2 Line 3` </code> This is extremely useful for logs, SQL, shaders, etc. ==== Common pitfalls to be aware of ==== Template literals use **backticks**, not **quotes** ''${}'' is not jQuery or shell syntax — it’s JS-only Don’t confuse ''${}'' with ''$(...)'' (shell / jQuery) ==== TL;DR ==== * ''${...}'' is **expression interpolation inside template literals** * It replaces string concatenation cleanly * It improves readability and formatter behavior * It’s safe, modern, and efficient * It’s the idiomatic way to build strings in modern JS programming/javascrip.txt Last modified: 2026/01/26 09:44by mh