스코프 (Scope)
블럭 안의 변수는 블럭 안에서만 유효함
변수, 함수, 클래스가 어디까지 유효한지 나타내는 범위 영역
식별자간 이름충돌 방지 메모리 절약
- 참고 문서 :
https://developer.mozilla.org/en-US/docs/Glossary/Scope
Scope - MDN Web Docs Glossary: Definitions of Web-related terms | MDN
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
developer.mozilla.org
블럭 외부에서는 블럭 내부의 변수를 참조할 수 없음
{
const a = 'a';
console.log(a);
}
const b = 'b';
console.log(a);
// 에러 발생 ReferenceError: a is not defined
함수 외부에서는 함수 내부의 변수를 참조할 수 없음
function scope() {
const greeting = 'Hi Hello Bonjour';
console.log(greeting);
}
console.log(greeting);
//에러 발생 ReferenceError: greeting is not defined
함수 외부에서는 함수의 매개변수를 참조할 수 없음
function multiply(a,b) {
console.log(a,b);
}
console.log(a,b);
//에러 발생
- 전역변수, 전역 스코프 (글로벌 변수, 글로벌 스코프)
: 외부에서 선언되어 전역적으로 어디에서나 사용 가능한 변수 - 지역변수, 지약 스코프(로컬 변수, 로컬 스코프)
: 스코프 내에서 선언된 변수
가비지 컬렉터 (Garbage Collector)
자바스크립트에서 사용하지 않는 할당된 메모리는 가비지 컬렉터가 청소해줌
스코프 내에서 정의된 변수는 한 번 사용되고나면 메모리가 정리됨
✅ 효율적인 메모리 관리를 위해서는 변수가 전역에 정의되는 것 보다 필요한 스코프 내에 정의해서 사용해버리는 것이 좋음
- 참고 문서 :
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Memory_Management
Memory management - JavaScript | MDN
Low-level languages like C, have manual memory management primitives such as malloc() and free(). In contrast, JavaScript automatically allocates memory when objects are created and frees it when they are not used anymore (garbage collection). This automat
developer.mozilla.org
'Frontend > JavaScript' 카테고리의 다른 글
[JavaScript] 실행 컨텍스트 (Execution Context) / 렉시컬 환경 (Lexical Environment) / 호이스팅(hoisting) / var (0) | 2023.01.21 |
---|---|
[JavaScript] null 체크하는 법, 널 병합 연산자 (Nullish Coalescing Operator ??) (0) | 2023.01.20 |
[JavaScript] 클릭시 특정 태그 위치로 이동 scrollIntoView (0) | 2023.01.19 |
[JavaScript] Intersection Observer (0) | 2023.01.18 |
[JavaScript] 이터레이션 프로토콜 (Iteration Protocol) / 이터러블 (Iterable) (0) | 2023.01.14 |