JavaScript #8 ~ Strings and Template Literals

hjbaek91·2021년 5월 31일

[Learn] JavaScript

목록 보기

When creating long strings in code, it is common usage to use the '+' operator to combine strings together. However, this method can become very tedious once variables are involved. Instead, we can use a much simpler method known as template literals.

Using template literals helps us write cleaner code strings with less complication. This method is also very useful when we need to modify the value of an existing string variable.

Lets say that there were a group of variables that could be used to create a string variable. What could be the best approach to make things easier.

const firstName = 'John';
const job = 'Developer';
const birthYear = 1995;
const year = 2021;

Normally, we would try to use the basic string rule to show the result. However, as mentioned before, this can make things complicated in the future when we need to change our value in a variable.

const description = "I'm " + firstName + ', a ' + (year - birthYear) + ' years old ' + job + '!';

Just writing out the whole string format felt very tedious and complicated. Instead, we could use a template literal to simplify the code. When using template literals, we use a backtick instead of the regular quotation marks. Additionally, would also use '${}' to express variables.

const description = `I'm ${firstName}, a ${year - birthYear} year old ${job}!`;

The code looks much cleaner now! 👍

Improving Everyday

0개의 댓글