This is something no one tells you normally 🤯.
Template Literals is a different way of formatting a String. In Normal String formatting, we use the addition operator to concatenate two string values or other values in order to form a string.
Example for normal string format:
let concat = 'Hello ' + 'John your age is ' + 19;
console.log(concat);
// Results: Hello John your age is 19
But a template literal is something different. backtick is used for opening and closing of the string and inside it happens the magic.
Normally we use a string in the template literals addition operator isn't used. To insert other variables or other types of value we used this syntax ${value}
. Inside those brackets, we can insert any type of value, or variable and can perform operations.
Example for template literals
let concat = `Hello John your age is ${19}`;
console.log(concat);
// Results: Hello John your age is 19
Perform Operations in Template literal
We can perform operators inside those brackets. No matter what operation it is. After the operation is performed then it will be concatenated with the string.
An example is given below:
let dob = 2000;
let age = `John your age is ${2023 - dob}`;
console.log(age);
// Result: John your age is 23
Ternary Operator in Template Literals
Ternary operator can be used inside a template literals. Which we cannot do with the normal string concatenation. It allows use to make the statement more dynamic.
Example:
let dob = 2000;
let driverslicense = `John you are ${2023 - dob > 20 ? 'eligible' : 'not eligible'} to apply for Drivers license`;
console.log(driverslicense);
// Result: John you are eligible to apply for Drivers license
In the above example 2023 - dob
is checked whether its greater than 20 or not then based on the result the respected string is executed. As simple as it is.
Remember you cannot use any kind of conditional statement except a ternary operator, loops cannot be used, and Whole objects cannot be used instead individual values can be. functions and arrays can be used. Over it if there is anything that can also be used go for it because these are the things I have worked with.