본문 바로가기
개발 언어/자바스크립트 33가지 개념

[JavaScript 33가지 개념] 06. 함수 범위, 블록 범위, 렉시컬(lexical) 범위

by 우주다람쥐 2022. 6. 6.
반응형

 

변수를 선언하는 위치에 따라 사용할 수 있는 범위가 다르게 정의된다.

기본적으로 javascript 변수는 함수 범위로 동작한다.

 

1. 함수 범위

function nameFunc() {
  var name1 = 'tom';
  console.log('1-1', name1);
}

nameFunc();
console.log('1-2', name1);

if (true) {
  var name2 = 'bob';
  console.log('2-1', name2);
}

console.log('2-2', name2);

위 처럼 변수를 선언하고 호출하면 아래와 같은 결과가 나온다.

 

1-1 tom
1-2 undefined error
2-1 bob
2-2 bob

1-2에서 에러가 발생하는 걸 확인할 수 있다. 즉, 변수 선언 후 사용은 함수 범위로만 사용이 가능하다.

기본적으로 var 는 함수 단위로 동작하기 때문에 if문과 같이 함수가 아닌 범위에서 만든 변수는 호출할 수 있다.

 

2. 블록 범위

ES6에서 부터는 const, let이 도입되었다.

그러면서 블록 범위로 변화했는데 위와 같은 예시로 사용해보면 다음과 같다.

 

function nameFunc() {
  const name1 = 'tom';
  console.log('1-1', name1);
}

nameFunc();
console.log('1-2', name1);

if (true) {
  const name2 = 'bob';
  console.log('2-1', name2);
}

console.log('2-2', name2);
1-1 tom
1-2 undefined error
2-1 bob
2-2 undefined error

블록 단위로 변수의 선언과 사용이 가능하다보니 if문 안에서 생성된 내용도 밖에서는 사용할 수 없다.

 

 

3. 렉시컬(Lexical)

렉시컬 스코프(Lexical Scope)는 함수를 선언하는 위치에 따라 동작하는 걸 말한다.

 

var x = 1;

const first = () => {
  var x = 10;
  second();
};

const second = () => {
  console.log(x);
};

first();
second();

이렇게 하면 10으로 출력될 것 같지만 둘다 1로 출력된다.

그러나 위와 같은 특성을 사용하는 건 권장하지 않는다. (아니 쓰면 안 된다고 생각한다!! 같은 변수명을 여러 군데서 선언해서 쓰다니...)

 

그래서 아래와 같이 사용하면 global로 선언된 변수는 예상한 대로 둘다 10으로 출력된다.

 

let x = 1;

const first = () => {
  x = 10;
  second();
};

const second = () => {
  console.log(x);
};

first();
second();

 

이걸 보면서 변수명 선언은 명시적이고 독립적이어야 개발자가 코드를 이해하는데 좀 더 직관적으로 이해할 수 있다고 본다.

혼자서 개발한다면 문제가 없을 수도 있겠지만 함께 개발하는 상황에서는 es6 도입, 블록 범위 두 가지를 지켜가며 개발하는게 좋다.

 

 

참고자료

- https://www.deadcoderising.com/2017-04-11-es6-var-let-and-const-the-battle-between-function-scope-and-block-scope/

 

ES6: var, let and const — The battle between function scope and block scope

In the pre-ES6 era, there was only one way of declaring variables in JavaScript — being the usage of var. var has always had this special aura of misconception — this probably because of how the behaviour of variables declared with var distinguishes fr

www.deadcoderising.com

 

- https://ljtaek2.tistory.com/145

 

자바스크립트 - 렉시컬 스코프(Lexical Scope)

들어가기에 앞서, Closure(클로져)를 이해하기 위해서는 반드시 렉시컬 스코프(Lexical Scope)를 이해해야 한다. 렉시컬 스코프란(Lexical Scope)란? 함수를 어디서 호출하는지가 아니라 어디에 선언하였

ljtaek2.tistory.com

 

반응형

댓글