
Getting to Know Template Strings

Photo By Unsplash on Unsplash
Template strings are similar to string data types, representing textual data. Template strings were introduced in ES6 and are used by enclosing the data within backticks (`).
For those who have trouble finding the backtick symbol, you can locate it on your keyboard at the top-left corner, just below the Esc key.
The presence of template strings makes it easier to handle string data, making them more powerful than regular strings. This is because template strings allow for Multiple-line Strings, Expression Interpolation, and Tagged Templates, which are commonly used in coding.
If you want to display a string with multiple lines, you usually need to use a backslash \n for line breaks and concatenation (+) to join strings.
// dengan menggunakan string
console.log('string baris pertama \n' + 'string baris kedua')
// akan lebih mudah bila menggunakan template string
console.log(`string baris pertama string baris kedua'
Expression Interpolation is written using a dollar sign and curly brackets (${}), which function to insert variables into a string.
const nama = 'iqbal'
const kota= 'pontianak'
console.log(`nama saya adalah ${nama} dan saya tinggal dikota ${kota}`)
Tagged Template
A function can be parsed into a string using a tagged template. After the function is parsed and manipulated, the tagged template will return it as a string.
const nama = 'iqbal';
const umur = 23;
const taggedTemplate = (strings, namaSaya, umurSaya) => {
let str1 = strings[0]; // halo nama saya
let str2 = strings[1]; // dan umur saya
return `${str1}${namaSaya}${str2}${umurSaya}`;
}
const hasil = taggedTemplate `halo nama saya ${nama} dan umur saya ${umur}`;
console.log(hasil); // output -> halo nama saya iqbal dan umur saya 23
That’s the explanation of Getting to Know Template Strings that Mangcoding can share. Hopefully, this article is useful and provides new insights for you. If you have constructive feedback or suggestions, feel free to leave a comment or contact us via email and Mangcoding’s social media.
Source : Muhammadiqbal