템플릿 리터럴이 무엇인가요?

0

기술면접 - JS

목록 보기
13/18

템플릿 리터럴이 무엇인가요?

템플릿 리터럴의 개념 및 예시

템플릿 리터럴은 JavaScript 및 TypeScript에서 문자열을 생성하기 위한 문법적인 기능입니다. 템플릿 리터럴을 사용하면 문자열 안에 변수, 표현식, 줄바꿈 등을 쉽게 포함할 수 있습니다. 아래는 템플릿 리터럴의 몇 가지 예시입니다:

  1. 변수 삽입:
const name = 'John';
const age = 30;

const message = `My name is ${name} and I'm ${age} years old.`;
console.log(message);
// 출력: My name is John and I'm 30 years old.
  1. 표현식 삽입:
const a = 10;
const b = 5;

const result = `The sum of ${a} and ${b} is ${a + b}.`;
console.log(result);
// 출력: The sum of 10 and 5 is 15.
  1. 다중 줄 문자열:
const multiLine = `
  This is
  a multi-line
  string.
`;
console.log(multiLine);
// 출력:
//   This is
//   a multi-line
//   string.
  1. 태그드 템플릿 리터럴:
function customTag(strings, ...values) {
  console.log(strings);
  console.log(values);
}

const item = 'apple';
const price = 2.5;

customTag`The price of ${item} is ${price} dollars.`;
// 출력:
//   [ 'The price of ', ' is ', ' dollars.' ]
//   [ 'apple', 2.5 ]

위의 예시에서 ` 문자로 문자열을 감싸고, ${} 안에 변수 또는 표현식을 넣어서 템플릿 리터럴을 작성할 수 있습니다. 이렇게 작성된 템플릿 리터럴은 해당 변수 또는 표현식의 값으로 대체됩니다. 또한, 다중 줄 문자열을 쉽게 작성하거나 태그드 템플릿 리터럴을 사용하여 특별한 처리를 할 수도 있습니다.

profile
지치지 않는 백엔드 개발자 김성주입니다 :)

0개의 댓글