 |
Template literals MDN documentation |
On MDN, template literals are defined as string literals allowing embedded expressions. It makes composing strings with variables and multiline strings more convenient. Instead of using quotes to enclose strings, you use back-ticks ` ` to encase template literals.
Template Literals
For examples:
Without template string
let transitionDuration = 1;
let transitionDelay = 2;
console.log('Transition time is ' + (transitionDuration + transitionDelay));
Using template literal
let transitionDuration = 1;
let transitionDelay = 2;
console.log(`Transition time is $(transitionDuration + transitionDelay)`);
Nesting template literals
const screenWidth = `width: ${isDesktop() ? '90' :`${(isTablet() ? '95' : '100')}` }vw`;
 |
Template Literal Example |
Tagged Template Literals
Using Tagged Template Literals, you can parse template literals with a function. The first argument of a tag function is an array consists of strings broken at embedded expressions.
For example:
The template string here is `today is ${today}`
let today = 'Tue'
console.log`today is ${today}`
["today is ", "", raw: Array(2)] "Tue" // return from console.log
let today = 'Tue'
let tomorrow = ‘Wed'
console.log`today is ${today} and tomorrow will be ${tomorrow}.`
["today is ", " and tomorrow will be ", ".", raw: Array(3)] "Tue" "Wed"
 |
Tagged Template Literal Example |
 |
Tagged Template Literal Example |
We can use the expressions in the string literals to execute a function.
For example:
var addOne = (toAdd) => { return 1 + toAdd }
addOne(1) // return 2
var addTwo = (input, toAdd) => {
return 2 + toAdd;
}
var number = 7;
addTwo`add this ${number}` // return 9
addTwo`add this ${number > 10 ? 5 : 2}` // return 4
 |
Function stored in a variable |
 |
Tagged Template Literal without handling input |
 |
Tag Function with Template Literal
|
|
Because Tagged Template Literal, there is a new way called
styled-components to write CSS for React and React Native components.
Note
1) It is used in
graphql-tag for JavaScript applications.
Thank you for reading!
Comments
Post a Comment