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
728x90

✨ 말 그대로 '기본 값 설정' + '나머지' + '펼치기(?)'를 사용하는 방법이다.

💻Example Code

Default
function f1(x, y = 0) {
  return x + y; }

console.log(f1(3) === 3);

Rest
function f2(x, ...y) {
  return x * y.length; }

console.log(f2(2, 'hi', true) === 4);

Spread
function f3(x, y, z) {
  return x + y + z; }

console.log(f3(...[1, 2, 3]) === 6);

실행 결과(모두 true로 출력)

😋 먼저, parameter default는 재귀함수를 사용할 때 유용하다. 굳이 선언을 따로 하지 않고, parameter에서 해결이 가능하기 때문이다. Rest는 아직 사용해본 적은 없지만, 종종 쓰일 것 같고, Spread는 알고리즘 문제를 풀 때와 개발을 할 때 꽤 많이 썼다. 특히, fibonacci, sort 그리고 levelWidth 등 다양한 곳에서 사용했다. 몇 줄이나 나와야할 코드를 단 한 줄로 해결하기에 굉장히 좋다.

👉 자세한 내용은 https://babeljs.io/docs/en/learn/#default-rest-spread

 

Babel · The compiler for next generation JavaScript

The compiler for next generation JavaScript

babeljs.io

 

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

Template Strings  (0) 2020.01.25

+ Recent posts