본문 바로가기

자바스크립트

[Javascript] - 템플릿 문자열

 

 

 

 

 

 

 

 

템플릿 문자열이  무엇일까  일단  다음 코드를 보자 

const name = 'paul';
const age = '42';
const address = 'newyork';
const introduce = "Hi my name is" + name + "and im'+ age + 'years old' + 'i living in' + address
console.log(introduce)
// Hi my name is paul and im 42 years old i living in seoul 
      

변수에 값을 할당한뒤  문자열을 만들어  출력하는 코드다  이런 방식도 있지만  훨씬 직관적으로 코드를 표현할 수 있는 방법이 있다  바로 '템플릿 문자열' 이다 

 

const name = 'paul';
const age = '42';
const address = 'newyork';
const introduce = `Hi my name is ${name} and im ${age} years old i living in ${address}`
console.log(introduce)
// Hi my name is paul and im 42 years old i living in seoul 

문자열을 만들때 큰따음표가 아닌  백틱을 넣어주고  넣어주고자 하는 변수를 ${ } 안에 넣어 이어 붙여주면 된다 훨씬  자연스럽고  직관적이지 않은가