본문 바로가기

Javascript

Javascript / 자바스크립트 최신 문법 ES6

 

Shorthand property names

const name = 'elie';
const age = '18';

# basic
const elie2 = {
	name : name,
    age : age,
}

# Shorthand property names
const elie2 = {
	name,
    age,
}

 

 

Destructuring assignment

//object
const student = {
	name : 'anna',
    level : 1,
}


// basic
{
	const name = student.name;
    const level = student.level;
    console.log(name, level); // anna 1
}


//ES6 - 같은이름을 변수로
{
	const {name, level} = student; // student에 key, value들이 각 name, level에 맞게 할당됨
    console.log(name, level); // anna 1
}

//ES6 - 같은이름을 변수로
{
	const {name:studentName, level:studentLevel} = student; // 
    console.log(studentName, studentLevel); // anna 1
}
//Array (object와 동일)

const animals = ['dog', 'cat'];

//basic
{
	const first = animals[0];
    const second = animals[1];
    
    console.log(first, second); // dog cat
}


//ES6
{
	const [first, second] = animals; // 순서대로 할당됨
    console.log(first, second);
}

 

 

Spread syntax

{
	const obj1 = {key: 'key1'};
    const obj2 = {key: 'key2'};
    const array = [obj1, obj2];
    
    
    //array copy
    const arrayCopy = [...array]; 
   
	const arrayCopy2 = [...array, {key : 'key3'}]; // 복사후 새 아이템 추가
    
    
    //object copy (array와 동일)
    const obj3 = { ...obj1 };
    
    
    //array concatenation 
    const fruits1 = ['apple', 'pear']
    const fruits2 = ['banana', 'kiwi']
    conste fruits = [...fruits1, ...fruits2]; //['apple', 'pear', 'banana', 'kiwi']
    
    
    //object merge
    const dog1 = { dog1: 'dog1'}
    const dog2 = { dog2: 'dog2'}
    const dog = {...dog1, ...dog2} // dog1과 dog2의 key값이 같으면 뒤에 key값이 덮어씌움
   
}

copy할 경우 object의 주소값(참조값)을 가져와서 같은곳을 바라보기때문에 

A를 B에 복사하는 경우 A의 값을 변경하면, B의 값도 변경됨

 

copy 하는 경우 map, foreach 사용하지않고 ...으로 복사해 올 수 있음(각각 낱개로 가지고와서 복사함)

 

 

Default parameters

{

	function printMessage(ms){
    		console.log(ms);
    	}
   
   printMessage('hi');
   printMessage(); // this case =>  error
}

// ES6문법
{
	function printMessage(message = 'default message'){
    	console.log(ms);
    }
   
   printMessage('hi');
   printMessage(); // 'default message'
}

 

 

Ternary Operator (삼항연산자)

condition ? exprIfTrue : exprIfFalse 

// basic
if(person > 18) {
	console.log('yes');
}else {
	console.log('no');
}

// ES6 
person > 18? 'yes':'no'

 

Template Literals

 

{
	const weather = 'sunny';
    const temparature = '16';
    


// basic
	console.log('Today weather is' + weather + 'and temperature is' +temparature);
    

// ES6 문법
	console.log('Today weather is ${weather} and temperature is ${temparature}');
    

    
    
}

 

 

출처 | 드림코딩 by 엘리

https://www.youtube.com/watch?v=36HrZHzPeuY 

자바스크립트 최신 문법 (ES6, ES11) | 모르면 후회 하는 최신 문법과 사용법 정리

반응형