Language/JavaScript
[JavaScript] var, let ,const 변수 선언 알고 쓰자
DevL1
2023. 6. 3. 23:33
변수 선언 방식( var - let const )에 대한 차이 알고 쓰자
Hoisting과 Scope의 개념이 필요하다.
Hoisting
모든 변수 선언은 호이스트된다.
코드로 보면 이해하기 쉬울 것이다.
function hoisting() {
var banana; // banana 변수는 호이스트 되었습니다.
console.log(banana); // undefined
banana = "monkey"; // banana : "monkey"
console.log(banana); // "monkey"
}
hoisting();
※ 안되는 Hoisting 예제
function hoisting() {
console.log(banana);
let banana = "monkey";
}
hoisting();
function hoisting() {
console.log(banana);
const banana = "monkey";
}
hoisting();
ReferenceError: Cannot access 'banana' before initialization
※ Hoisting한 형태가 아닌 예제
{
var hoisting = "Not Hoisting";
}
console.log(hoisting ); // "Not Hoisting"
Scope
어떤 변수들에 접근할 수 있는가를 정의.
전역 스코프
변수가 function 바깥이나 {}바깥에서 선언된 경우.
const globalVariable = 'variable';
아래 예제를 보시죠
const hello = 'Hello World!'
function learnScop () {
console.log(hello);
}
console.log(hello); // 'Hello World!'
learnScop(); // 'Hello World!'
전역 스코프를 이용하여 변수를 선언할 수 있지만, 전역 변수는 선언 시 주의가 필요합니다.
※ 잘못된 예시
// 잘못된 예시
let variable = 'Hi World!';
let variable = 'Bye World!';
SyntaxError: Identifier 'variable' has already been declared
※ 주의해야 하는 예시 - 덮어씀
var variable = 'Hi World!';
var variable = 'Bye World!';
console.log(variable) // Bye World