๐ก ๋์ ๋ชจ๋ ์๋ฐ์คํฌ๋ฆฝํธ ํต์ฌ ๊ฐ์ด๋๋ฅผ ์ฝ๊ณ ์ ๋ฆฌํฉ๋๋ค.
4.1 ๋ฌธ์์ด ์ฝ์
// ES5
var name = "Alberto";
var greeting = 'Hello my name is ' + name;
console.log(greeting);
// Hello my name is Alberto
// ES6
let name = "Alberto";
const greeting = `Hello my name is ${name}`;
console.log(greeting);
// Hello my name is Alberto
4.2 ํํ์ ์ฝ์
// ES5
var a = 1;
var b = 10;
console.log('1 * 10 is ' + ( a * b));
// 1 * 10 is 10
// ES6
var a = 1;
var b = 10;
console.log(`1 * 10 is ${a * b}`);
// 1 * 10 is 10
4.3 ์ฌ๋ฌ ์ค ๋ฌธ์์ด ์์ฑ
// ES5
// ๊ฐ ํ๋ง๋ค backslash ์ถ๊ฐ ํ์
var text = "hello, \
my name is Alberto \
how are you?\ "
// ES6
const content = `hello,
my name is Alberto
how are you?`;
4.4 ์ค์ฒฉ ํ ํ๋ฆฟ
const people = [{
name: 'Alberto',
age: 27
},{
name: 'Caroline',
age: 27
},{
name: 'Josh',
age: 31
}];
const markup = `
<ul>
${people.map(person => `<li> ${person.name}</li>`)}
</ul>
`;
console.log(markup);
// <ul>
// <li> Alberto</li>,<li> Caroline</li>,<li> Josh</li>
// </ul>
4.5 ์ผํญ ์ฐ์ฐ์ ์ถ๊ฐํ๊ธฐ
const artist = {
name: "Bon Jovi",
age: 56,
};
// artist ๊ฐ์ฒด์ song ํ๋กํผํฐ๊ฐ ์์ ๋๋ง ๋ฌธ์ฅ์ ์ถ๊ฐํ๊ณ , ์์ผ๋ฉด ์๋ฌด ๊ฒ๋ ๋ฐํํ์ง ์์
const text = `
<div>
<p> ${artist.name} is ${artist.age} years old ${artist.song ? `and wrote the song ${artist.song}` : '' }
</p>
</div>
`
// <div>
// <p> Bon Jovi is 56 years old
// </p>
// </div>
const artist = {
name: "Trent Reznor",
age: 53,
song: 'Hurt'
};
// <div>
// <p> Trent Reznor is 53 years old and wrote the song Hurt
// </p>
// </div>
4.6 ํ ํ๋ฆฟ ๋ฆฌํฐ๋ด์ ํจ์ ์ ๋ฌํ๊ธฐ
๋ค์ ์์ ์ฝ๋์ฒ๋ผ ํ ํ๋ฆฟ ๋ฆฌํฐ๋ด ๋ด์ ํจ์๋ฅผ ์ ๋ฌํ ์๋ ์๋ค.
const groceries = {
meat: "pork chop",
veggie: "salad",
fruit: "apple",
others: ['mushrooms', 'instant noodles', 'instant soup'],
}
function groceryList(others) {
return `
<p>
${others.map( other => ` <span>${other}</span>`).join('\n')}
</p>
`;
}
const markup = `
<div>
<p>${groceries.meat}</p>
<p>${groceries.veggie}</p>
<p>${groceries.fruit}</p>
<p>${groceryList(groceries.others)}</p> // ํ
ํ๋ฆฟ ๋ฆฌํฐ๋ด ๋ด์ ํจ์ ์ ๋ฌ
<div>
`
// <div>
// <p>pork chop</p>
// <p>salad</p>
// <p>apple</p>
// <p>
// <p>
// <span>mushrooms</span>
// <span>instant noodles</span>
// <span>instant soup</span>
// </p>
// </p>
// <div>
4.7 ํ๊ทธ๋ ํ ํ๋ฆฟ ๋ฆฌํฐ๋ด
ํจ์๋ฅผ ํ๊ทธํ์ฌ ํ ํ๋ฆฟ ๋ฆฌํฐ๋ด์ ์คํํ๋ฉด ํ ํ๋ฆฟ ๋ฆฌํฐ๋ด ๋ด๋ถ์ ์๋ ๋ชจ๋ ํญ๋ชฉ์ด ํ๊ทธ๋ ํจ์์ parameter๋ก ์ ๊ณต๋๋ค.
let person = "Alberto";
let age = 25;
function myTag(strings,personName,personAge){
let str = strings[1];
let ageStr;
personAge > 50 ? ageStr = "grandpa" : ageStr = "youngster";
return personName + str + ageStr;
}
let sentence = myTag`${person} is a ${age}`;
console.log(sentence);
// Alberto is a youngster