09. Scope

wonyoung·2023년 5월 22일

JavaScript 기초 문법

목록 보기
9/13
post-thumbnail

Scope란?


  • 변수 혹은 상수에 접근할 수 있는 범위
  • 모듈/함수 내 코드에서 동일한 변수 사용시 간섭을 줄이는 용도
  • Scope는 Global Scope와 Local Scope의 타입으로 구분
    Global Scope: 전역에 선언되어 어디에서도 접근 가능
    Local Scope(block, function level scope): 특정 지역에 선언되어, 해당 지역 내에서만 접근가능

Scope 범위


Scope 예제 (1)


// global scope
let A = 1;
let B = 2;
{
  // local scope
  let C = 3;
  let D = 4;
  
  console.log(A); // output: 1
  console.log(B); // output: 2
}

console.log(C); // ReferenceError: C is not defined

Scope 예제 (2)


// global scope
let A = 1;
{
  // local scope
  let C = 3;
  let D = 4;
  
  console.log(C); // output: 3
  {
    // local scope
    let C = 5;
    let D = 6;
    
    console.log(C); // output: 5
  }
}

Scope 예제 (3)


// Global Level Scope
let index = 1000;

function local_func() { // Function Level Scope 
  let index = 100;
  for (let index = 0; index <10; index++) { // Block Level Scope
    console.log(index); // output: 0~9
  }
  console.log(index); // output: 100
}
local_func();
console.log(index); // output: 1000
profile
지치지 않는 개발자가 되자!

0개의 댓글