programming/beginner

[js] template literal

솧이 2022. 9. 11. 20:56

▶ template literal

backstick(` `) 문자를 사용한 문자열 포맷팅이다

문자열 안에서 ${변수}, ${값}

let myname = "홍길동";
let age = 25;

console.log(`저의 이름은 ${myname}이고 나이는 ${age}입니다`);
console.log(`welcome ${2000 + 22} years`);

 

* 줄바꿈 가능하다

console.log(`안녕하세요
		반갑습니다`);

 

* template literal도 내부적으로 문자열 연결 연산(+)

const myObject = {name : "John", age : 40};
const arr1 = [10, 20, 30];

console.log('myObject =', myObject);

 

* 'myObject = ' + myObject.toString()  --> [object Object] 결과가 나온다

  모든 object는 자신을 문자열로 표현하는 toString() 메소드들을 제공한다 

console.log(`myObject = ${myObject}`);  
// 템플릿 리터럴로  myObject = { name: 'John', age: 40 } 이런식으로 출력 안된다
console.log('myObject = ' + myObject);

 

'programming > beginner' 카테고리의 다른 글

[js] function  (0) 2022.09.11
[js] null, undefined  (0) 2022.09.11
[js] object  (0) 2022.09.11
[js] datatype (literal, string, number, array, object, null, undefined)  (0) 2022.09.11
[js] operator  (0) 2022.09.11