let name = 'subin';
console.log(name);
// 'subin'
name = 'testUser';
console.log(name);
// 'testUser'
let name = 'name';
// Error SyntaxError: Identifier 'name' has already been declared
const test = 'test'; console.log(test);
// test
test = 'test1';
console.log(test);
// Error Assignment to constant variable.
const test = 'test'; console.log(test);
// Error SyntaxError: Identifier 'name' has already been declared
console.log(age); // undefined
age = 27;
var age;
console.log(age); // 27
var 키워드를 이용할 경우 변수의 선언을 항상 컨텍스트 내의 최상위로 끌어올린다.
이로인해 undefined 로 값이 초기화 되기 때문에, 선언하기 전에도 값을 사용할 수 있다.
호이스팅은 변수만 해당되는 것이 아니라, 함수도 가능하며 함수의 호출을 첫 줄에서 하고 마지막 줄에 함수를 정의해도 문제가 없다.


console.log(fruit);
// undefined
var fruit;
fruit = 'apple';
console.log(fruit);
// apple
그럼 과연 let과 const에서는 호이스팅이 안 될까? 🤨
아니다.. 된다!!! 🙆🏻♀️

console.log(fruit);
// ReferenceError 선언문 이전에 참조 불가
// 1. 선언
let fruit;
console.log(fruit);
// undefined
// 2. 초기화
fruit = 'apple';
console.log(fruit);
// apple
function num() {
for(var i = 0; i < 5; i++) {
console.log(i);
}
console.log('num : ', i);
}
num();
console.log(i);
/*
0
1
2
3
4
num : 5
*/
// i is not defined
함수 스코프이므로 i 접근 불가능.
function num() {
for(let i = 0; i < 5; i++) {
console.log(i);
}
console.log('num : ', i);
}
num();
console.log(i);
// Error ReferenceError: i is not defined
-외부에서 i 접근 불가능.
var score = 27;
if(score >= 19){
var result = true;
}
console.log(result);
// true
for(let i = 0; i < 3; i++){
console.log(i);
}
console.log(i);
// Error i is not defined

var 를 쓸 경우 호이스팅 문제가 있으며 변수 중복 선언이 가능하고 함수 이외에 변수는 전역 변수가 되므로 전역변수를 남발할 가능성이 매우 높다. 예측 불가능한 코드들.. var를 이제 더이상 놔주자.
출처
https://www.youtube.com/watch?v=OCCpGh4ujb8
https://onlydev.tistory.com/29
https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Statements/let
https://www.w3schools.com/js/js_hoisting.asp
https://namu.wiki/w/%ED%98%B8%EC%9D%B4%EC%8A%A4%ED%8C%85
https://medium.com/korbit-engineering/let%EA%B3%BC-const%EB%8A%94-%ED%98%B8%EC%9D%B4%EC%8A%A4%ED%8C%85-%EB%90%A0%EA%B9%8C-72fcf2fac365
https://dmitripavlutin.com/variables-lifecycle-and-why-let-is-not-hoisted/
https://noogoonaa.tistory.com/78