Before ES6 introduced template strings in 2015, JavaScript strings had limited syntax and functionality. Concatenating strings was possible, but it often led to complex and cumbersome code.
With the advent of ES6 template literals, you can now solve more intricate problems and concatenate strings with data values in a much smoother manner. Template literals offer a cleaner and safer syntax for working with strings, eliminating the hours of struggle with long string concatenation. Embrace the power of template literals to enhance your string manipulation and make your code more elegant and efficient.
Basic usage
The syntax of template strings is very simple, just use backticks instead of single or double quotes.
let msg = `A string`;
If we want to surround a special world with a single or double quote we can do that simply .. because we have used a different character to define our string.
Multiline strings
Template strings make multiline much simpler. we can simply add a line break where we want to, press enter, and there it is.
let msg = `Hi,
Good job.
Regards`;
so we can format our string to look as we wish.
Expressions
Template literals provide an easy way to contain placeholders and expressions into strings. You do so by using the ${…}
const name = 'Naya';
const msg = `Hi ${name}`;
Inside of the curly braces, it’s often gonna be a variable, but it could be a whole JavaScript expression or mathematical expression. Can be a function call, it can even be a template literal inside of that expression if you need it to be.
// Mathematical expression
const msg = `You have ${1+3} Dogs`;
// function call
const msg = `Hi ${nameFn()}`;
console.log(msg);
function nameFn() {
return "Naya";
}