global scope vs local scope

../jiwon/heo·2023년 8월 3일
0

javascript

목록 보기
2/5

1. 전역 스코프 (global-scope)란?

  • 전역 스코프는 어떤 함수 내에 속하지 않은 가장 바깥 영역을 말한다.
    전역 스코프에서 선언된 변수와 함수는 어느 곳에서든 접근할 수 있다.

👌 For example

// 전역 스코프에서 전역 변수를 선언합니다.
const globalVar = "I am a global variable";

function greet() {
  // greet 함수의 스코프
  console.log(globalVar); // 전역 스코프의 globalVar에 접근 가능
  console.log("Hello from the greet function");
}

function anotherFunction() {
  // anotherFunction 함수의 스코프
  console.log(globalVar); // 전역 스코프의 globalVar에 접근 가능
  console.log("Hello from another function");
}

greet(); // 출력: "I am a global variable" "Hello from the greet function"
anotherFunction(); // 출력: "I am a global variable" "Hello from another function"
console.log(globalVar); // 출력: "I am a global variable"

위 코드에서 globalVar 는 전역 스코프에서 선언되었기 때문에 greet 함수와 anotherFunction 함수 어디에서든 접근이 가능하다.


지역 스코프 (local-scope)란?

  • 지역 스코프는 함수 내부에서 선언된 변수와 함수가 해당 함수 내에서만 접근 가능한 영역을 말한다.

👌 For example


function myFunction() {
  // myFunction의 지역 스코프
  const localVar = "I am a local variable";
  console.log(localVar); // 지역 스코프의 localVar에 접근 가능

  function nestedFunction() {
    // nestedFunction의 지역 스코프
    console.log(localVar); // 지역 스코프의 localVar에 접근 가능
    console.log("Hello from the nested function");
  }

  nestedFunction();
}

myFunction(); // 출력: "I am a local variable" "I am a local variable" "Hello from the nested function"
console.log(localVar); // 오류: localVar는 지역 스코프 내에서만 존재합니다

위 코드에서 localVarmyFunction 함수의 지역 스코프에서 선언되었기 때문에 myFunction 함수와 nestedFunction 함수 내에서만 접근이 가능하다. nestedFunction 내부에서도 localVar에 접근이 가능하다. 그러나 myFunction 함수 바깥에서는 접근이 불가하다.

+++ Plus 개념

  • 내부 함수는 내부 함수를 감싼 외부 함수의 스코프에 접근할 수 있다. 이것을 "클로저(Closure)"라고 부른다.
profile
virtuous circle : 시도 - 구글링 - 문제해결 - 반복

0개의 댓글