함수는 항상 업데이트된 글로벌 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]
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"}
보통 쓰는 예는,
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";
// 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;
const greeting = (name = "Anonymous") => "Hello " + name;
console.log(greeting("John")); // Hello John
console.log(greeting()); // Hello Anonymous
const sum = (...args) => {
return args.reduce((a, b) => a + b, 0);
}
console.log(sum(1, 2, 3)); // 6
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에서만 작동하기 때문이다.