서버리스, planetscale
Var의 예측 불가능성을 보완하기 위해 ES6부터 let, const 키워드가 추가되었다. var는 잘 사용하지 않는다.
let x = "Global X"; // 전역변수
function a() {
let x = "Local X"; // 지역변수
console.log(x);
}
function b() {
console.log(x);
}
a();
b();
결과
Local X
Global X
var x = "Global X";
if (true) {
var x = "If X";
console.log("1", x);
}
console.log("2", x);
결과
1 If X
2 If X
let a = 10;
console.log(a);
const b = "abc";
console.log(b);
b = "abcd";
결과
10
abc
오류 발생
const myProfile = {
name: "ksh",
age: 20,
isRich: false,
};
console.log(myProfile);
myProfile.age = 30;
console.log(myProfile);
결과
{ name: 'ksh', age: 20, isRich: false }
{ name: 'ksh', age: 30, isRich: false }
const myProfile = {
name: "ksh",
age: 20,
isRich: false,
};
console.log(myProfile);
Object.freeze(myProfile);
myProfile.age = 30;
console.log(myProfile);
결과
{ name: 'ksh', age: 20, isRich: false }
{ name: 'ksh', age: 20, isRich: false }
console.log(x);
var x = "Hi!";
console.log(x);
결과
undefined
Hi!
console.log(x);
let x = "Hi!";
console.log(x);
결과
ReferenceError: Cannot access 'x' before initialization