/**
* Hoisting은 무엇인가?
*
* 모든 변수 선언문이 코드의 최상단으로 이동되는
* 것처럼 느껴지는 현상을 이야기한다
*/
console.log('hello');
console.log('world');
이렇게 콘솔창에 'hello' 와 'world'를 띄워보면
[Running] node "c:\Users\young hwan\Desktop\coding\Html,CSS,JavaScript\JavaScript\1_basics\6_hoisting.js"
hello
world
[Done] exited with code=0 in 0.2 seconds
당연히 이렇게 차례대로
hello
world 가 출력된다
var name;
console.log(name);
name = '갓용환';
console.log(name);
그럼 이렇게 var로 name 이란 변수를 선언만 하고 값을 주지않고 콘솔창에 띄우고
그다음에 name이라는 변수의 '갓용환'이라는 문자열값을 지정해 콘솔창에 띄우면
[Running] node "c:\Users\young hwan\Desktop\coding\Html,CSS,JavaScript\JavaScript\1_basics\6_hoisting.js"
undefined
갓용환
[Done] exited with code=0 in 0.213 seconds
name이란 변수를 선언만한 콘솔은 undefined
name이란 변수를 선언하고 '갓용환'이라는 값을 지정한 콘솔은
정상적으로 출력되는걸 볼 수있다
이것이 hoisting현상 이라고 한다
console.log(yongHwan);
let yongHwan = '갓용환';
똑같이 콘솔에 yongHwan이라는 변수를 띄우고
그 뒤에 let으로 yongHwan이라는 변수를 만들고 '갓용환'이라는 값을 지정했다
순서대로 console.log는 let으로 값을 정의하기 전의 변수이다(undefined)
let으로 선언한 변수는 console.log 다음순서로 선언했기 때문이다
console.log(yongHwan);
^
ReferenceError: Cannot access 'yongHwan' before initialization
at Object.<anonymous> (c:\Users\young hwan\Desktop\coding\Html,CSS,JavaScript\JavaScript\1_basics\6_hoisting.js:16:13)
at Module._compile (node:internal/modules/cjs/loader:1256:14)
at Module._extensions..js (node:internal/modules/cjs/loader:1310:10)
at Module.load (node:internal/modules/cjs/loader:1119:32)
at Module._load (node:internal/modules/cjs/loader:960:12)
at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:81:12)
at node:internal/main/run_main_module:23:47
Node.js v18.17.1
실행하면 이렇게 에러가 나는걸 볼 수 있다
ReferenceError: Cannot access 'yongHwan' before initialization
해당 문장은 'yongHwan'이라는 변수를 초기화를 하기전에 접근할수 없다는 뜻이라고 한다
console.log(yongHwan);
// let yongHwan = '갓용환';
그러면 이렇게 선언한 변수를 주석처리를 하고 console.log만 실행시켜보면
ReferenceError: yongHwan is not defined
이라는 에러가 뜬다
yongHwan은 정의되지 않았다는 에러이다
그러므로
console.log(yongHwan);
let yongHwan = '갓용환';
이렇게 코드를 작성했을때
console.log의 변수는 실제 존재는 하는것이다(undefined로 존재)
하지만 그다음으로 let 으로 변수를 선언했기 때문에
let으로 선언하는 순간이 오기 전으로 접근을 할 수 없게된다
이게 let과 const키워드로 변수를 선언하라는 이유라고 한다
위의것 처럼 hoisting현상을 var키워드는 막아주지 못하고(에러없이 실행이 된다)
let과 const로 값을 초기화(변수 값 지정)하기 전에 console.log에 변수를 지정하면
에러가 뜨기때문에 var키워드로 썻을때처럼 값을 미리 가져오는 버그를 방지할 수 있다