프로그래밍 언어/Javascript
자바스크립트 최신 문법 (ES6, ES11)
김곰댕
2021. 8. 27. 17:13
728x90
ES6
<!DOCTYPE html>
<html lang = "en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" consent="width=device-width, initial-scale=1.0" />
<title>Document</title>
<script src="es6-11/es6.js"></script>
</head>
<body></body>
</html>
Shorthand property names
const ellie1 = {name: 'Ellie', age: '18'};
const name = 'Ellie';
const age = '18';
const ellie2 = {name: name, age: age}; //위에서 선언한 변수 name의 값과 age의 값이 key와 value의 값으로 들어가게됨
//Shorthand property names 사용
const ellie3 = {name, age}; //key와 value의 이름이 동일한 경우 생략 가능
console.log(ellie1,ellie2,ellie3);

Destructuring Assignment
//Object
const student = {name: 'Anna', level: 1};
{
const name = student.name;
const level = student.level;
console.log(name, level);
}
//Destructuring Assignment 사용
{
const {name, level} = student;
console.log(name, level);
const {name: studentName, level: studentLevel} = student; //이름을 바꾸어서도 사용이 가능
console.log(studentName, studentLevel);
}
//array
const animals = ['🐯', '🐭'];
{
const first = animals[0];
const second = animals[1];
console.log(first, second);
}
//Destructuring Assignment 사용
{
const [first, second] = animals;
console.log(first,second);
}

Spread Syntax
const obj1 = {key: 'key1'};
const obj2 = {key: 'key2'};
const array = [obj1, obj2];
//array copy
//Spread Syntax 사용
//...array에 들어있는 아이템을 하나하나 낱개로 가져와 복사해오는것 (주소를 가져오는것이기 때문에 복사후 값을 변경하게 되면 전체에 반영이됨)
const arrayCopy = [...array];
console.log(array,arrayCopy);
const arrayCopy2 = [...array, {key: 'key3'}]; //기존의 내용을 복사하면서 새로운 내용을 추가
obj1.key = 'newKey';
console.log(array, arrayCopy, arrayCopy2);
//object copy
const obj3 = {...obj1};
console.log(obj3);
//array concatenation
const fruits1 = [' 🍊 ',' 🍋 '];
const fruits2 = [' 🍇 ',' 🍓 '];
const fruits = [...fruits1, ...fruits2]; //fruits1과 fruits2를 하나로 병합
console.log(fruits);
//object merge
const dog1 = {dog1: ' 🐕 '};
const dog2 = {dog2: ' 🐩 '};
const dog = {...dog1, ...dog2};
console.log(dog);
//key의 이름이 합치려는 2개의 오브젝트가 동일하면 뒤 오브젝트의 key값으로 덮어져서 쓰이게됨
const cat1 = {cat: ' 🐱 '};
const cat2 = {cat: ' 🐈 '};
const cat = {...cat1, ...cat2};
console.log(cat);

Default parameters
function printMessage(message)
{
if(message == null)
{
message = 'default message';
}
console.log(message);
}
printMessage('hello');
printMessage();

위의 코드를 Default parameters를 사용하여 수정하면
function printMessage(message = 'default message')
{
console.log(message);
}
printMessage('hello');
printMessage();

Ternary Operator
const isCat = true;
{
let component;
if(isCat)
{
component = '🐱';
}
else
{
component = '🐶';
}
console.log(component);
}

위의 코드를 ternary operator를 사용하여 수정하면
const component = isCat ? '🐱' : '🐶'; //위의 if else코드와 같은 의미
console.log(component);

Template Literals
const weather = '☀️';
const temparature = '16°C';
console.log('Today weather is ' + weather + ' and temparature is ' + temparature);
//Template Literals 사용
console.log(`Today weather is ${weather} and temparature is ${temparature}`);

ES11
<!DOCTYPE html>
<html lang = "en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" consent="width=device-width, initial-scale=1.0" />
<title>Document</title>
<script src="es6-11/es11.js"></script>
</head>
<body></body>
</html>
Optional Chaining
person1이라는 오브젝트 안에 name키, job오브젝트가 있고, job 오브젝ㅌ트 안에 title키, manager오브젝트가 있음
const person1 = {
name: 'Ellie',
job: {
title: 'S/W Engineer',
manager: {
name: 'Bob'
}
}};
const person2 = {name: 'Bob'};
{
function printManager(person)
{
console.log(person.job.manager.name);
}
printManager(person1); //Bob
//printManager(person2); //Error
}

직업이 없는 사람을 넣었을때 undefined가 출력되도록 위의 코드를 여러 방법으로 수정해보도록 하겠다.
1) 삼항연산자 사용
function printManager(person)
{
console.log(
person.job ? person.job.manager ? person.job.manager.name : undefined : undefined
);
}
printManager(person1); //Bob
printManager(person2); //undefined

2)
function printManager(person)
{
console.log(person.job && person.job.manager && person.job.manager.name)
}
printManager(person1);
printManager(person2);

3) Optional Chaining 사용
function printManager(person)
{
console.log(person.job?.manager?.name); //위의 코드와 같은 의미 / person의 job이 있으면, person의 manager가 있으면 name을 출력
}
printManager(person1);
printManager(person2);

Nullish Coalescing Operator
1) leftExpr || rightExpr : 왼쪽 코드가 false인 경우에만 오른쪽 코드가 실행
2) leftExpr ?? rightExpr : 왼쪽 코드가 null이거나 undefined인 경우에만 오른쪽 코드가 실행
//Logical OR operator
//false : false, '', 0, Null, undefined
{
const name = 'Ellie'; //true
const userName = name || 'Guest'; // ||앞의 값이 false일 때만 뒤에 실행
console.log(userName); //앞의 값이 true 이기 때문에 name에 저장된 값인 Ellie가 출력
}
{
const name = null; //false
const userName = name || 'Guest'; // ||앞의 값이 false일 때만 뒤에 실행
console.log(userName); //앞의 값이 false 이기 때문에 Guest가 출력
}

위 코드의 한계점
//Logical OR operator의 한계점
{
//아무런 이름을 입력하고 싶지 않은경우에도 Guest가 출력
const name = '';
const userName = name || 'Guest';
console.log(userName);
//0을 숫자로 받아오고 싶은 경우에도 false로 인식하여 뒤의 값이 출력
const num = 0;
const message = num || 'undefiend';
console.log(message);
}

Logical OR operator 코드 보완
const name = '';
const userName = name ?? 'Guest'; //이름이 있으면 name의 값을 사용하고 이름에 값이 없으면 Guest 출력
console.log(userName);
const num = 0;
const message = num ?? 'undefiend'; //num에 값이 있으면 num값 사용, 없으면 undefiend사용
console.log(message);
공백과 0이 그대로 출력됨

함수에도 사용이 가능
const result = getInitialState() ?? fetchFromServer(); //getInitialState()가 null이거나 undefined인 경우에 뒤에 함수 호출
console.log(result);
function getInitialState()
{
return null;
}
function fetchFromServer()
{
return 'Hiya from 💻'
}

728x90