nomad coder의 javascript ES6 이상 버전의 문법에 대한 강의를 들으면서 정리해둔 내용이다.

ES6 이후의 새로운 문법들이 총 정리 되어있는 포스팅이 없는 것 같아서 열심히 정리해 두었다. 

(노마드코더 와이프분인 lynn님에게 이메일 보내서 내 블로그에 게시해도 좋다는 회신을 받았음)

ES6이상 새로운 의 모~~~든 문법을 포함하는 내용이 아닐 수도 있지만, 대부분 포함되어 있을것임. 

 

 

1. const and let

 const name = ‘yeejun’  // read-only
 const person = {name: ‘yeejun’}  // 내부의 값은 바꿀수 있음. 
                                     person.name = ‘something'
                                  // 하지만 person 자체를 새로 할당 할 수는 없다 
 let은 var랑 비슷함. 근데 몇가지 차이가 있음.
 차이1 -> let은 자바스크립트가 컴파일되는 과정에서 hoisting 되지 않는다. 
         즉 var처럼 컴파일 과정에서 자동으로 선언과 할당을 분리시켜서 선언부를 맨 위로 올려버리지 않음.
         (이런 현상을 let의 temporal deadzone이라고 한다)
 차이2 -> var는 function scope를 갖지만, let과 const는 block scpoe ( = { } ) 를 갖는다.

 

 

2. 그러면 var는 더이상 미래가 없는건가?

더이상 안쓰는게 좋음. ECMA에서 var를 deprecated시키지 않는 이유는 이미 기존의 웹서비스에서 var를 많이 사용해놓은 상태이기 때문임.

 

 

3. Arrow Functions

Ex) const names = [’nico’,’lynn’]
    const hearts = names.map(item => item + ‘ hi’);
    // return을 명시하지 않았지만 같은 줄에 있다면 자동으로 return이 있다고 간주함(implicit return)
    console.log(hearts); 

this를 사용하는 경우 조심해야한다
화살표함수는 lexical scope상에서 this가 정의되어 버린다. 일반적인 함수의 this는 dynamic하게 결정되므로 자신을 실행시킨 exception context에 해당하는 object인 한단계 상위의 객체를 가리킨다.

 

 

4. Default value

ES6에서는 함수에 전달되는 파라미터에 디폴트값을 설정 할 수 있게 되었다.
Ex) function sayHi(aName){
 return ‘Hello ’ + ( aName || ‘annonymous’ )
}
   위 함수를 이제 이렇게 표현 가능함
function sayHi(aName = 'annonymous'){
 return ‘Hello ’ +  aName;
}

 

 

5. Strings (Template literal)

1.
cosnt sayHi = (aName = “anon”) => “hello” + aName + “ lovely~~”
console.log(sayHi()); 

sayHi 함수가 리턴하는 저 문자열을 이제 저렇게 번거롭게 코딩할 필요가 없다.
백틱이라는 것을 사용함.

cosnt sayHi = (aName = “anon”) => `hello ${aName} lovely~~` 
이렇게 string 내부에 표현식을 넣을 수 있다. 
${ } 내부에는 문자가 아니라, 변수를 포함한 자바스크립트 코드가 들어갈 수 있다.
${ } 내부에 함수를 정의할 수는 없음. 이런저런 실험을 스스로 해보면 좋을듯. 



2. js코드로 HTML소스를 가져올 수 있다.
예를들어 이런코드가 있다 치자.
const wrapper = document.querySelector(“.wrapper”);

const addWelcome = () => {
 const div = document.createElement(‘div’);
 const h1 = document.createElement(‘h1’);
 h1.innerText = “Hello”;
 h1.className = ‘sexytitle’
 div.append(h1);
 wrapper.append(div);
}

setTimeout(addWelcome, 5000);
Javascript 코드로 html 구조를 만들려는건데, 코드가 너무 길어진다.
이런 경우 template literal방식을 사용하면 엄청 간단하고 직관적으로 만들 수 있다. 
 const wrapper = document.querySelector(“.wrapper”);


const addWelcome = () => {
 const div = `
<div class=‘hello’>
<h1 class=’title’>Hello</h1>
</div>
`;
 wrapper.append(div);
}
백틱을 사용하면 띄어쓰기 뿐만 아니라 엔터나 탭까지도 모두 실제 엘리먼트 구조에 반영된다.
Cf) console.log(“


Hahaha

“) 
이렇게 콘솔로그를 확인하면 에러나면서 안됨. 근데 백틱을 사용하면 엔더친거까지 다 인식해서 출력된다. 



3. 또 다른 하나의 예시
const wrapper = document.querySelector(“.wrapper”);
const friends = [“me”, “lynn”, “dal”, “mark”];
const list = `
    <h1>People I love</h1>
    <ul>
      ${friends.map(friends => `<li>${friend}</li>.join(“”)`}
    </ul>
`

wrapper.innerHTML = list;



4.template literal을 이용해서 함수를 호출할 수가 있다.
    fn( ) 이게 아니라 fn` ` 이렇게 사용할 수가 있다는 것. 
    Html 태그를 만드는 함수를 하나 정의해서 예시를 보자.
    const styled = aElement => {
        const el = document.createElement(aElement);
        return args => {
            const styles = args[0];
            el.style = styles;
            return el;
        } 
}

const title = styled(“h1”)`
    background-color: red;
    color: blue;
`;
const subtitle = styled(“span”)`
    color: green;
`;
title.innerText = “We just cloned”;
Subtitle.innerText = “Styled Components”;

document.body.append(title, subtitle);

 

 

6. es6에 처음 도입된 string method들

1. includes
    Ex) const isEmail = email => email.includes(“@”);
        console.log(isEmail(“adslijf@naver.com”)


2. repeat
    const CC_NUMBER = “6060”;
    const displayName = `${“*”.repeat(10)}${CC_NUMBER}`;
    console.log(displayName);


3. startsWith, endsWith
    const name = “Mr.Nicolas”;
    console.log(name.startsWith(“Mr”));  //true
    endsWith도 같은방식으로 작동한다.(끝나는 부분을 확인)

 

 

7. Array

1. Array.of 
    const friends = Array.of(“nico”, “lynn”, “yeejun”)
    console.log(friends) //[“nico”, “lynn”, “yeejun”]  



2. Array.from
    HTML태그로 버튼이 여러개 만들어져 있다고 했을때,
    const buttons = document.getElementsByClassName(“btn”);

    forEach메소드를 통해 buttons에 이벤트를 걸어주려고 해도, buttons는 현재 
    배열이 아니라 유사배열(array-like object)이기 때문에 forEach를 사용 할 수 없다.
    이때 유사배열을 배열로 바꾸기 위해 Array.from을 사용한다.
    
    const buttons = document.getElementsByClassName(“btn”);
    Array.from(buttons).forEach(button => {
        Button.addEventListener(“click”, () => console.log(“클릭중”)
    });
    


3. Array.find
    => find는 true를 반환하는 첫 번째 요소를 리턴한다.
    const friends = [
        “nico@gmail.com”,
        “lynn@gmail.com”,
        “dal@yahoo.com”,
        “mark@hotmail.com”,
        “flynn@korea.com"
    ];
    
    const target = friends.find(friend => friend.includes(“@korea.com"));
    friends 배열 내부의 각 요소들이 처음부터 차례대로 friend라는 파라미터로 넘겨진다.
    console.log(target);



4. Array.findIndex
    => 해당 요소(element)가 배열의 어디 위치에 있는지 알고싶을때
        해당 요소(element)의 위치를 알아내서 수정하려고 할 때 유용함.
    const check = () => friends.findIndex(friend => friend.includes(“@korea.com"));
    let target = check();
    If(target !== -1){
        console.log(target);      // 4


        const username = friends[target].split(“@”)[0];
        const email = “korea.co.kr”;
        friends[target] = `${username}@${email}`;
        target = check();
    }
    console.log(target);      // -1 



5. Array.fill
    => array를 채우는 메소드임. 시작하는 인덱스와 끝나는 지점의 인덱스를 지정해 줄 수 있다.
        friends.fill(‘*’.repeat(‘5’), 1, 3);
        console.log(friends)



6. Array.includes
    => 배열 안에 어떤 요소가 있는지 확인한다. 있다면 true를 반환한다. 
        let check = friends.includes(“nico@gmail.com”);
        console.log(check);

 

 

8. Destructuring

    object 또는 array의 요소들을 바깥으로 끄집어낸다. 

1. Object destructuring
    => 뽑아내고 싶은 객체 내부의 값을 동일한 변수에 할당하여 끄집어낸다.
const setting = {
    notifications: {
        follow: true,
        alerts: true,
        unfollow: false
    },
    color: {
        theme: “dark"
    }
};

const follow = setting.notifications.follow <- 이거랑 같은 문법 구조를 destructuring으로 만들거임.

const {
    notifications: { follow },
    color    
} = settings;
값을 담고있는 객체 변수를 ‘=’의 좌측이 아니라 우측에 쓴다. 

console.log(follow)    // true
console.log(color)    // {theme: “dark”}

여기에 defualt값을 넣어 줄 수도 있다.
만약 notifications 객체 내부에 follow라는게 없다면 false를 할당하도록 해보자
(이렇게 처리하지 않고 에러가 발생하게 되면 어플의 작동 자체에 문제가 될 수가 있다.)
const {
    notifications: { follow = false },
    color    
} = settings;

근데 여기에서 notifications라는 객체 자체가 없다면 어떻게 할까?
이때는 빈 객체 {}를 notifications라는 객체의 defualt값으로 지정하도록 해보자.

const {
    notifications: { follow = false } = {},
    color    
} = settings;

애초에 setting 객체 안에 follow라는 값이 없었다면,
console.log(follow)    // false  -> notifications는 빈 객체, follow는 false가 기본값으로 할당됨



2. Array destructuring
    => 주로 가져온 정보를 변경시키지 않을때 유용하게 사용할 수 있다.

const days = [“Mon”, “Tue”, “Wed”, “Thu”, “Fri”, “Sat”, “Sund”]

배열은 객체와 달리 key가 없고 컴퓨터가 내부적으로 기억하고 있는 순서(index)만 있기 때문에, 그 순서에 따라 destructuring 해준다.
const [mon, tue, wed] = days;
console.log(mon, tue, wed);

배열의 디스트럭쳐링도 기본값을 설정 할 수 있다.
const days = [“Mon”, “Tue”, “Wed”];
const [mon, tue, wed, thu=“Thu"] = days;
console.log(mon, tue, wed, thu);

함수가 리턴하는 값에 대해서도 디스트럭쳐링을 사용 할 수 있다. (객체도 마찬가지임)
const days = () => [“Mon”, “Tue”, “Wed”];
const [mon, tue, wed, thu=“Thu"] = days;  <- mon, tue 등은 변수로써 사용되므로 ‘’로 감싸지 않는다.
console.log(mon, tue, wed, thu);



3. Renaming
    => js문법으로 작성되지 않은 어떤 Api를 받았다고 하자
const setting = {
    color: {
        chosen_color: “dark”  <— 변수명 형태를 보니 파이썬으로 만들어진 코드인듯
    }
};

const {
    color:{ chosen_color = “light” }
} = setting;

console.log(chosenColor);

기존의 js 문법으로 저 snakeCase 변수명을 camelCase 형태로 바꾸려면 이렇게 해야한다.
const chosenColor = setting.color.chosen_color || “light”;
이러한 기존 방식은 너무 길고 보기싫음.

이제는 아래와 같이 하면 된다.
먼저 받아온 api 데이터에서 chosen_color라는 변수명을 chosenColor로 바꾸고, 만약 
이게 없다면 chosenColor의 기본값으로 “light”를 할당해준다.
const {
    color:{ chosen_color: chosenColor = “light” }
} = settings;

만약에 디스트럭쳐링으로 새로운 변수를 만들어 할당하는 것이 아니라, 기존의 변수에 할당하고 싶다면 아래와 같이 객체를
소괄호로 감싸준다. 디스트럭처링 앞에 const를 해주지 않았기 땜에 기존의 변수를 찾는다.

let chosenColor = “blue”;   <— 이걸 const로 정의하면 다시 다른 값을 할당 할 수 없다
console.log(chosenColor);  // blue

({
    color:{ chosen_color: chosenColor = “light” }
} = settings);
console.log(chosenColor);  // dark



4. Function destructuring 
    => 함수와 함께 사용하는 object restructuring

function saveSettings({follow, alert, color = ‘blue’}){
 console.log(color);
}

saveSettings({
 follow: true,
 alert: true,
 mkt: false
});

또는 아래와 같이 코딩해도 됨.

function saveSettings({notifications, color = { theme }){
 console.log(color);
}


saveSettings(
 notifications: {
  follow: true,
  alert: true,
  mkt: false
},
 color: {
  theme: “blue” 
});



5. Value Shorthands
    => 가져오려는 값이 담겨있는 변수명과 그 값을 담기 위한 변수명을 동일하게 작성 할 경우에 간결하게 사용하는 문법.
 checkFollow, checkAlert 라는 함수가 정의되어 있다고 하자.

cosnt follow = checkFollow();
cosnt alert = checkAlert();

const settings = {
 Notifications: {
  follow: follow,
  alert: alert
 }
} 

위의 settings를 아래와 같이 정의하면 됨.

const settings = {
 Notifications: {
  follow,
  alert
 }
} 



6. Swapping and Skipping
    => 이건 새로운 기능이라기 보다 es6문법을 활용해서, 이미 어떤 변수에 할당되어 있는 값들을 서로 바꾸는 스킬임.

let mon = “Sat”;
let sat = “Mon”;

Array destructuring을 이용해서 할당된 값들을 서로 바꾼다.
[sat, mon] = [mon, sat];
 
아래에 한 것처럼 array에서 특정 값을 생략할 수도 있다.

const days = [“mon”, “tue”, “wed”, “thu”]
const [ , , , thu, fri] = days;   <- 생략하고 싶은 부분은 그냥 콤마로 채우면 됨

 

 

 

 

 

 

 

 

 

 

 

'PROGRAMING > Javascript' 카테고리의 다른 글

Javascript ES6 문법 총정리(2)  (0) 2020.08.01
Javascript 런타임  (0) 2019.10.10

+ Recent posts