행복해지자
article thumbnail
Published 2023. 3. 9. 17:50
JS - ES6 문법 파헤치기 (1) JS

1.  destructuring (구조 분해 할당) 

const player = {
  name: "GwonSewon",
  club: "proteen",
  address:{
    city:"Busan"
  }
}

console.log(player.address.city)

const {name, club, address:{city}} = player;

console.log(name,club,city)//destructuring

console.log(`${name} lives in ${city}!`)//template literal

예제코드

 

구조 분해 할당은 구조체(Object),배열(Array)등을 변수에 나누어 담는 것을 말한다. 

이코드를 쓰면 조금 더 코드가 깔끔해지고 보기 쉬워진다

 

마지막 Console.log()는 Template literal을 사용했는데 문자열 사이에 들어가는 변수를 직관적으로 볼 수 있게 해준다.

//destructuring 을 최대한 사용해서 코드 바꾸기

/** 원본 */
function addressMaker2 (address) {
  const newAddress2 = {
    city: address.city,
    state: address.state,
    country: 'United States'
  }
  console.log(newAddress2.city, newAddress2.state, newAddress2.country)
}
/** 바꾼 코드 */
function addressMaker3 (address) {
  const {city,state} = address;
  const newAddress3 = {city,state,country : 'United States'}
  console.log(newAddress3.city, newAddress3.state, newAddress3.country)
}

2. for of loop

JS - ES6 문법에서는 자바의 Enhanced For Loop , 파이썬의 for in 과 같이 for 를 사용할 수 있게 해준다 아래는 예제 코드다

/** for of loop */
 let incomes = [3500,3700,4000]
 let total = 0

 for (const income of incomes) {
   console.log(income)
   total += income
 }
 console.log(total)

 let fullName = "Gwon 5e vvon"
 for ( const char of fullName){
   console.log(char)
 }

/** challenge  (for of loop)*/
 const student = [
   {name:'Gwon',city: 'busan'},
   {name:'se',city: 'Paris'},
   {name:'won',city: 'japen'}
 ]

 for (const {name, city} of student) console.log(`${name} lives in ${city}`)

3. 전개연산자 (Spread Operator)

 /**Spread Operator */
 let contacts = ['Mary', 'Joel', 'Danny']

 contacts.push('John')

 let personalFriends = ['David', ...contacts, ' Lily']
 console.log(personalFriends)

/** challenge */

 const shoppingList = ['eggs','milk','butter']
 const actualList = ['cigarrrete','liquor', 'beer',...shoppingList]
 console.log(shoppingList)

이것의 결과는 actualList뒤에 shoppingList의 결과가 붙어나온다

다른 Object에서도 사용이 가능하다

 

4. 제약없는 함수 전달인자 개수 (multiful arguments)

 

/** multiful arguments */
function fnc(nums) {
  console.log(nums);
}
fnc(4);
//4
function fnc2(...nums) {
  console.log(nums);
}
fnc2(4, 3, 34, 4, 3, 4);
//[4,3,34,4,3,4)
function fnc3(nums) {
  console.log(arguments);
}

fnc3(1, 2, 3, 4, 5, 6);
//1,2,3,4,5,6

이런식으로 여러 파라미터를 받을 수 있다

 

5.  익명함수 , 화살표함수 (anonymous function, arrow function)

/**anonymous function */
const lunchMenu = function () {
  return "I'm going to eat pizza for lunch";
//그대로 나옴

/**arrow function */

const dinnerMenu = () => {
  return "I'm going to eat chicken for dinner";
};
//역시 그대로 나옴

const dinnerMenu2 = () => "I'm going to eat a burger for dinner";
//return생략했으나 그대로 나옴

const DinnerMenu3 = (food) => `I'm going to eat a ${food} for dinner`;
//파라미터가 없으면 undefined가 들어감
console.log(DinnerMenu3("gukbab"));
//food 위치에 gukbab이 들어감

const DinnerMenu4 = (food = "burger") =>
  `I'm going to eat a ${food} for dinner`;
//파라미터에 값을 안넣으면 burger가 들어감
console.log(DinnerMenu4());

이런식으로 함수를 정리해서 볼 수도 간소화 할 수 있다.

 

6. includes

/** include  */
 let numArray = [1, 2, 3, 4, 5, 6, 7, 8, 9];
 console.log(numArray.includes(2));
 //true

includes는 배열에 파라미터의 값이 있는지 확인하는 기능을한다

7.var vs let vs const

/** var , let ,const */
 if (false) {
   var example = 5;
   let example2 = 6;
 }
 console.log(example, example2);
//example2 에서 에러발생
const example3 = 5
example3 = 1
//에러발생 const는 변경불가
console.log(example3);


const example4 = [];
example4.push(3);
//배열 안을 바꾸기 때문에 사용이 가능하다
console.log(example4);

const example5 = {};
example5.firstName = "Dylan";
//이것도한 object안 속성을 바꾸기 때문에 가능하다

console.log(example5);

var = 전역 선언이 가능하다

let = 지역 변수로만 작용한다

const = 상수로서 수정이 불가하다

 

이번에는 여기서 마치겟습니다.

'JS' 카테고리의 다른 글

JS - ES6 문법 파헤치기 (3)  (0) 2023.03.22
JS - ES6 문법 파헤치기 (2)  (0) 2023.03.09
profile

행복해지자

@qlido

포스팅이 좋았다면 "좋아요❤️" 또는 "구독👍🏻" 해주세요!