TIL no.11 ES6 1

이조은·2020년 7월 11일
0

TIL self-study

목록 보기
11/19
post-thumbnail
  • var vs let vs const
    var: 재선언 가능. globally or locally (inside a function). reassign 가능.
    let: 재선언 불가능. reassign 가능.
    const: 재선언 불가능. reassign 불가능.
함수는 항상 업데이트된 글로벌 i변수 값을 참조한다. 그래서 printNumTwo()는 2가 아닌 3을 가진다.
var printNumTwo;
for (var i = 0; i < 3; i++) {
  if (i === 2) {
    printNumTwo = function() {
      return i;
    };
  }
}
console.log(printNumTwo());
// returns 3

i는 global scope에서 선언되지 않고 for loop 안에서 선언되었다. for loop 안의 let에 의해서 i 변수가 0, 1, 2의 값을 가지기 때문에 2라는 옳은 값을 리턴한다.
'use strict';
let printNumTwo;
for (let i = 0; i < 3; i++) {
  if (i === 2) {
    printNumTwo = function() {
      return i;
    };
  }
}
console.log(printNumTwo());
// returns 2
console.log(i);
// returns "i is not defined"
  • immutable value(const)는 대문자로 입력하고, mutable value(var, let)는 소문자 혹은 카멜케이스로 입력한다.

  • Objects(including arrays and functions) assigned to a variable using const are still mutable. Using the const declaration only prevents reassignment of the variable identifier.

"use strict";
const s = [5, 6, 7];
s = [1, 2, 3]; // throws error, trying to assign a const
s[2] = 45; // works just as it would with an array declared with var or let
console.log(s); // returns [5, 6, 45]
  • const만으로는 데이터를 변형시키는 것을 보호할 수 없다. Object.freeze를 사용하면 데이터를 변형을 피할 수 있다. 오브젝트가 한번 frozen되면 데이터를 바꾸려는 어떠한 시도도 에러 없이 거절된다.
let obj = {
  name:"FreeCodeCamp",
  review:"Awesome"
};
Object.freeze(obj);
obj.review = "bad"; // will be ignored. Mutation not allowed
obj.newProp = "Test"; // will be ignored. Mutation not allowed
console.log(obj); 
// { name: "FreeCodeCamp", review:"Awesome"}
  • 자바스크립트에서는 함수에 이름을 지을 필요가 없는 경우가 많다. 특히 함수를 아규먼트로서 다른 함수에 넘길 때 그렇다. 대신에 inline function을 만들 수 있다. 이 함수를 어디서도 다시 쓰지 않을 것이기 때문에 이름을 붙일 필요가 없다.
보통 쓰는 예는,
const myFunc = function() {
  const myVar = "value";
  return myVar;
}

arrow function 구문을 쓰면,
const myFunc = () => {
  const myVar = "value";
  return myVar;
}

function body가 없고 리턴 값만 있을 때, arrow function에서는 return 단어를 생략할 수 있다. 코드를 둘러싼 괄호도 역시 생략 가능하다.
const myFunc = () => "value";
  • arrow functions with parameters
// doubles input value and returns it
const doubler = (item) => item * 2;

// the same function, without the argument parentheses
const doubler = item => item * 2;

// multiplies the first input value by the second and returns it
const multiplier = (item, multi) => item * multi;
  • set default parameters for your functions
const greeting = (name = "Anonymous") => "Hello " + name;

console.log(greeting("John")); // Hello John
console.log(greeting()); // Hello Anonymous
  • rest parameter: rest parameter를 함수의 패러미터로 쓰는 것도 가능하다. 이로써 다양한 수의 아규먼트를 받는 함수를 만들 수 있다. rest parameter는 args어레이를 체크할 필요를 줄여주고 map(), filter(), reduce()를 페러미터어레이에 적용하는 것을 돕는다.
const sum = (...args) => {
  return args.reduce((a, b) => a + b, 0);
}
console.log(sum(1, 2, 3)); // 6
  • spread operator: ...arr returns an unpacked array. It spreads the array.
const arr = [6, 89, 3, 45];
const maximus = Math.max(...arr); // returns 89

const spreaded = ...arr; // will throw a syntax error. 왜냐하면 spread operator는 an argument to a function or in an array literal에서만 작동하기 때문이다.
  • destructuring assignment
profile
싱글벙글

0개의 댓글