본문 바로가기
Frontend/JavaScript

[JavaScript] 스코프 (Scope) / 가비지 컬렉터 (Garbage Collector)

by 민두이 2023. 1. 20.
728x90
반응형

스코프 (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

 

 

728x90