✳️ MDN definition : The scope is the current context of execution in which values and expressions are "visible" or can be referenced. If a variable or expression is not in the current scope, it will not be available for use. Scopes can also be layered in a hierarchy, so that child scopes have access to parent scopes, but not vice versa.
예제 코드
let name = 'Anna'; function showName() { let name = 'Bell'; // 지역 변수 console.log(name); // 두 번째 출력 } console.log(name); // 첫 번째 출력 showName(); console.log(name); // 세 번째 출력
해설 :
첫 번째 출력 : 첫째줄의let name = 'Anna';
를 가져옴.
showName 함수 안쪽에 선언된 지역 변수 name에 접근 불가능하기 때문.두 번째 출력 : 함수 안에서 선언한 name이라는 지역 변수(
let name = 'Bell';
) 출력. 변수 이름이 전역 변수와 똑같지만 지역 변수가 전역 변수보다 우선순위가 높으므로 지역 변수 name이 출력됨.(쉐도잉(variable shadowing) 현상 발생 : 동일한 변수 이름으로 인해 바깥쪽 변수가 안쪽 변수에 의해 가려지는 현상)세 번째 출력은 첫 번째 출력과 마찬가지로 전역 변수 name을 출력.(
let name = 'Anna';
) 지역 변수에 선언된 name 변수는 안쪽 스코프이므로 접근이 불가능하기 때문.
1. 블록 스코프(block scope) : 중괄호를 기준으로 범위가 구분됨.
2. 함수 스코프(function scope) : function 키워드가 등장하는 함수 선언식 및 함수 표현식으로 만들어짐.
❗️ 주의점 : 같은 함수여도 화살표 함수를 사용하면 블록 스코프로 취급됨!
var
키워드로 정의한 변수는 블록 스코프를 무시하고, 함수 스코프만 따름.
❕예외 : 화살표 함수의 블록 스코프는 무시하지 않음.- 함수 스코프는 함수의 실행부터 종료까지이고, var 선언은 함수 스코프의 최상단에 선언됨.
- 선언 키워드가 없는 선언은 최고 스코프에 선언되고, 함수의 실행 전까지 선언되지 않은 것으로 취급됨.
- var는 블록 스코프 기준을 무시하므로,
var
보다는let
으로 변수 선언을 하는 것을 권장.
+) var declarations, wherever they occur, are processed before any code is executed. This is called hoisting*. Thier initial value isundefined
.
+) The scope of a variable declared with var is its current execution context and closures thereof, which is either the enclosing function and functions declared within it, or, for variables declared outside any function, global. Duplicate variable declarations using var will not trigger an error, even in strict mode, and the variable will not lose its value, unless another assignment is performed.
let
키워드가 안전한 이유 : const
키워드를 사용하는 것을 권장함.⟹ 가장 큰 차이점은 유효범위! var
는 블록 스코프 바깥에서도 접근 가능함!
✒️ MDN 예제 :
Blocks only scopelet
andconst
declarations, but notvar
declarations.{ var x = 1; } console.log(x); // 1 { const x = 1; } console.log(x); // ReferenceError: x is not defined
var
로 선언했으면 해당 함수 스코프 바깥에서 호출 가능함.let/const
로 선언했으면 바깥에서 호출 불가능!window 객체
브라우저에 존재함. 브라우저 창을 대표하는 객체이나, 브라우저 창과 관계없이 전역 항목도 담고 있음.
var 로 선언된 전역 변수와 전역 함수는 window 객체에 속함
예시) 개발자도구에서 var 로 선언한 전역함수가 window.함수로 불러와짐
var
는 블록 스코프를 무시하며, 재선언을 해도 에러를 내지 않음.name = 'Jin
), 해당 변수는 var로 선언한 전역 변수처럼 취급됨.'use strict'
입력)✒️ 참고자료
🔗 Function Scope & Block Scope in JS
🔹Function Scope: When a variable is declared inside a function, it is only accessible within that function and cannot be used outside that function.
🔹Block Scope: A variable when declared inside the if or switch conditions or inside for or while loops, are accessible within that particular condition or loop. To be consise the variables declared inside the {curly braces} are called as within block scope.🔸
var
is called as function scope that is if a variable is declared using var keyword it will be accessible throughout the function.
🔸let
&const
are also called as block scope that is they are accessible within that particular block.
📚 추가로 공부할 것 :