ES6문법이 사용되기 전에는 "var"을 사용했습니다. ES6문법이 사용되면서 변수 선언할 때 var, let, const를 사용합니다. var를 사용했을 때와 let, const를 사용했을 때 차이가 있습니다.
var korean = "Hangeul";
console.log(korean) // Hangeul
var korean = "Hangug-eo";
console.log(korean) // Hangug-eo
let korean = "Hangeul";
let korean = "Hangug-eo";
// Uncaught SyntaxError: Identifier 'korean' has already been declared
const ganadara = "ga,na,da,ra";
const ganadara = "ma,ba,sa";
// Uncaught SyntaxError: Identifier 'ganadara' has already been declared
// let //
let korean = "Hangeul";
console.log(korean); // 'Hangeul'
korean = "Hangug-eo";
console.log(korean); // 'Hangug-eo;
// const //
const ganadara;
// Error message ---> Uncaught SyntaxError: Missing initializer in const declaration
const ganadara = "ma,ba,sa";
ganadara = "ganadara";
// Error message ---> Uncaught TypeError: Assignment to constant variable.
var wolf = 3;
let sheep = 0;
function fence () {
var wolf = 0;
console.log('wolf_of_fence =', wolf); // wolf_of_fence = 0
let sheep = 17;
console.log('sheep_of_fence =', sheep); // sheep_of_fence = 17
}
fence();
console.log('wolf_outside =', wolf); // wolf_outside = 3;
console.log('sheep_outside =', sheep); // sheep_outside = 0;
var a = 1;
console.log(a); // 1
if (true) {
var a = 1234;
console.log(a); // 1234
}
console.log(a); // 1234
let b = 1;
console.log(b); // 1
if (true) {
let b = 1234;
console.log(b); // 1234
}
console.log(b); // 1
참고
https://poiemaweb.com/es6-block-scope
https://gist.github.com/LeoHeo/7c2a2a6dbcf80becaaa1e61e90091e5d
https://blueshw.github.io/2017/03/28/ES-var-VS-const-VS-let/