728x90

✨ 문자열과 변수를 함께 쓰는 형식(``)
(``는 백틱(Back-ticks)이라고 부른다)

💻Example Code

const TemplateStrings1 = `This is a template string.`;
const TemplateStrings2 = `In ES5 this is
not legal.`;
const name = 'David';
const TemplateStrings3 = `Hello ${name}, how are you?`;
const TemplateStrings4 = String.raw`In ES5 "\n" is a line-feed.`;

console.log(TemplateStrings1);
console.log(TemplateStrings2);
console.log(TemplateStrings3);
console.log(TemplateStrings4);

실행 결과

😋 TemplateString1처럼 일반적인 문자열처럼 사용할 수 있으며,
TemplateString2처럼 line-feed 입력 없이 줄바꿈을 할 수 있다.
TemplateString3처럼 문자열에 변수를 섞어 쓸 수 있으며,
TemplateString4처럼 String.raw와 함께 이스케이프 문자를 그대로 표현할 수 있다.

사용할 때 `을 열고 `로 닫아주면 되며, 문자열 안에 변수를 넣고 싶을 때는 ${변수명}을 작성해 주면 된다.

API를 사용할 때 Template Strings를 사용하면 굉장히 편리하다.

fetch에서 URL에 Template Strings를 적용한 코드

그리고 아래와 같이 안에 삼항연산자를 넣어 값을 비교할 수도 있다.

Template Strings안에 Ternary(삼항연산자)를 사용한 코드

👉 자세한 내용은 https://babeljs.io/docs/en/learn/#template-strings

 

Babel · The compiler for next generation JavaScript

The compiler for next generation JavaScript

babeljs.io

 

'JavaScript > ES5, ES6+' 카테고리의 다른 글

Default + Rest + Spread  (0) 2019.12.31

+ Recent posts