변수 선언 방식( 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
'Language > JavaScript' 카테고리의 다른 글
JavaScript의 Fetch 메서드는 왜 await를 두 번 사용하는가? (6) | 2024.11.11 |
---|---|
JavaScript로 API 호출 어떻게 하는 건데? (0) | 2024.05.06 |
[JavaScript] 날씨 앱 만들기(OpenWeatherMap API) (0) | 2024.05.05 |
[JavaScript] 쿠키(Cookie) 어떻게 다루는가? (1) | 2023.07.13 |
JavaScript의 Fetch 메서드와 이중 Await 패턴 이해하기 (0) | 2023.06.22 |