-
스코프(scope)와 호이스팅(hoisting)Javascript 2023. 4. 10. 23:06반응형
스코프(Scope)
변수의 유효범위. 선언한 변수가 영향을 미치는 범위를 의미함.
호이스팅(Hoisting)
인터프리터가 변수와 함수의 메모리 공간을 선언 전에 미리 할당하는 것
변수의 선언과 초기화를 분리 후, 선언만 코드의 최상단으로 옮기는 것
(자바스크립트는 초기화를 제외한 선언만 호이스팅한다.)
→ 함수나 변수 선언하기 전에 호출해도 에러가 발생하지 않음
*인터프리터 : 프로그래밍 언어의 소스 코드를 바로 실행하는 프로그램
var 재선언 O, 재할당(타입 변경도 가능) O / 함수 스코프 (또는 전역 스코프)
더보기블록 기준으로 스코프가 생기지 않아, 코드블록 내에 변수를 선언했어도 해당 변수는 전역변수가 된다.var로 선언한 변수는 어디서든 참조할 수 있으나, 변수에 할당하기 전에는 값은 undeined(undefined로 초기화)로 출력→ var 선언은 함수 실행 전에 처리 (호이스팅) 되나, 할당은 호이스팅 되지 않음let 재선언 X, 재할당 O
const(상수) 재선언 X , 재할당 X - 변수 선언시 초기값 꼭 대입해서 사용
더보기var와 달리 let과 const로 선언한 변수도 호이스팅 대상이나, undefined로 초기화하지 않고 에러가 발생한다.
let과 const는 var와 달리 블록 기준의 스코프를 가진다.
📍참고 사이트 :
https://fromnowwon.tistory.com/entry/var-let-const-scope
https://fromnowwon.tistory.com/entry/for%EB%AC%B8-let
'Javascript' 카테고리의 다른 글
요소 높이 맞추기 (0) 2024.08.07 비동기 vs 동기 (0) 2023.06.28 자바스크립트 특징 (0) 2023.04.27