var, let, const 키워드

Yoo Jong Hyeon·2023년 5월 23일
0

Front-end & JS

목록 보기
7/8
post-thumbnail

var 키워드

변수 중복 선언 허용

var x = 1;
var y = 1;

var x = 100; // x = 100 (1)
var y; // y (2)

console.log(x); // 100
console.log(y); // 1

위 예제의 x 변수와 y 변수는 중복 선언되었다.

이 때 자바스크립트 엔진에 의해 초기화 문이 있는 변수 선언문(1)은 var 키워드가 없는 것처럼 동작하고, 초기화문이 없는 변수 선언문(2)은 무시된다.

함수 레벨 스코프(function level scope)

var 키워드로 선언한 변수는 함수의 코드 블록만을 지역 스코프(local scope)로 인정한다.

var x = 1;
var i = 10;

if (true) {
  var x = 10;
}

for (var i = 0; i < 5; i++) {
  console.log(i); // 0 1 2 3 4
}

console.log(x); // 10
console.log(i); // 5

위 예제에서 보듯 함수 레벨 스코프를 지원하는 var 키워드는, 전역 변수의 남발과 변수 중복선언의 위험성을 내포한다.

변수 호이스팅(variable hoisting)

var 키워드로 선언된 변수는 변수 호이스팅(variable hoisting)에 의해 변수 선언문이 스코프의 선두로 끌어 올려진 것처럼 동작한다.

// var test;
console.log(test); // undefined

test = 100;

console.log(test); // 100

var test; // 변수 호이스팅(variable hoisting)에 의해 스코프의 선두로 끌어 올려진 것 처럼 동작한다.

변수 선언문 이전에 변수를 참조하는 것은 변수 호이스팅에 의해 문법적인 오류가 발생하진 않지만, 프로그램의 흐름을 꼬이게 만들어 코드의 가독성을 떨어뜨리고, 개발자의 실수를 야기할 수 있다.


let 키워드

변수 중복 선언 금지

ES6에서 추가된 새로운 변수 선언 키워드인 let 키워드는 이름이 같은 변수를 중복 선언하면 문법 에러(SyntaxError)가 발생한다.

let x = 1;

let x = 100; // SyntaxError: Identifier 'x' has already been declared
//     at Object.compileFunction (node:vm:360:18)
//     at wrapSafe (node:internal/modules/cjs/loader:1055:15)
//     at Module._compile (node:internal/modules/cjs/loader:1090:27)
//     at Object.Module._extensions..js (node:internal/modules/cjs/loader:1180:10)
//     at Module.load (node:internal/modules/cjs/loader:1004:32)
//     at Function.Module._load (node:internal/modules/cjs/loader:839:12)
//     at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:81:12)
//     at node:internal/main/run_main_module:17:47

console.log(x);

블록 레벨 스코프(block-level scope)

let 키워드로 선언한 변수는 모든 코드 블록(function, if, for, while, try/catch ...)을 지역 스코프로 인정하는 블록 레벨 스코프(block-level scope)를 따른다.

let x = 1;
console.log(x); // 1

{
  let x = 10;
  console.log(x); // 10

  let y = 100;
}

console.log(y); // ReferenceError: y is not defined
//     at Object.<anonymous> (c:\Users\bitcamp\git\mjs\test.js:11:13)
//     at Module._compile (node:internal/modules/cjs/loader:1126:14)
//     at Object.Module._extensions..js (node:internal/modules/cjs/loader:1180:10)
//     at Module.load (node:internal/modules/cjs/loader:1004:32)
//     at Function.Module._load (node:internal/modules/cjs/loader:839:12)
//     at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:81:12)
//     at node:internal/main/run_main_module:17:47

변수 호이스팅(variable hoisting)

let 키워드로 선언한 변수를 변수 선언문 이전에 참조하면 참조 에러(ReferenceError)가 발생한다. 이는 let 키워드로 선언한 변수는 선언 단계와 초기화 단계가 분리되어 진행되기 때문이다.

자바스크립트 엔진에 의해 런타임 전 암묵적으로 선언 단계가 먼저 실행되지만, 초기화 단계는 변수 선언문에 도달했을 때 실행된다.

// 선언 단계

// 일시적 사각지대(Temporal Dead Zone; TDZ)
console.log(foo); // ReferenceError: Cannot access 'foo' before initialization
//     at Object.<anonymous> (c:\Users\bitcamp\git\mjs\test.js:2:13)
//     at Module._compile (node:internal/modules/cjs/loader:1126:14)
//     at Object.Module._extensions..js (node:internal/modules/cjs/loader:1180:10)
//     at Module.load (node:internal/modules/cjs/loader:1004:32)
//     at Function.Module._load (node:internal/modules/cjs/loader:839:12)
//     at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:81:12)
//     at node:internal/main/run_main_module:17:47

// 초기화 단계
let foo;
console.log(foo); // undefined

// 할당 단계
foo = 1;
console.log(foo); // 1

자바스크립트는 ES6에서 도입된 let, const를 포함해서 모든 선언(var, let, const, function, function*, class 등)을 호이스팅(hoisting)한다. 단, ES6에서 도입된 let, const, class를 사용한 선언문은 호이스팅이 발생하지 않는 것처럼 동작한다.

전역 객체(global object)와 암묵적 전역(implicit global)

var 키워드로 선언한 전역 변수와 전역 함수 및 선언하지 않은 변수에 값을 할당한 암묵적 전역은 전역 객체 window의 프로퍼티가 된다. 그러나 우리가 이 사실을 알지 못했던 이유는 전역 객체 window의 프로퍼티를 참조할 때 window를 생략할 수 있기 때문이다.

// 전역 변수(global variable)
var x = 1;

// 암묵적 전역(implicit global)
y = 2;

// 전역 함수(global function)
function foo() {}

console.log(window.x); // 1
console.log(x); // 1

console.log(window.y); // 2
console.log(y); // 2

console.log(window.foo); // ƒ foo() {}
console.log(foo); // ƒ foo() {}

let 키워드로 선언한 전역 변수는 전역 객체의 프로퍼티가 아니다. let 전역 변수는 보이지 않는 개념적인 블록, 즉 전역 렉시컬 환경의 선언적 환경 레코드 내에 존재하게 된다.

// 이 예제는 브라우저 환경에서 실행해야 한다.
let x = 1;

console.log(window.x); // undefined
console.log(x); // 1

const 키워드

const 키워드는 상수(constant)를 선언하기 위해 사용한다.

선언과 초기화

const 키워드로 선언한 변수는 반드시 선언과 동시에 초기화해야 한다.

const x = 10;
const y; // SyntaxError: Missing initializer in const declaration
//     at Object.compileFunction (node:vm:360:18)
//     at wrapSafe (node:internal/modules/cjs/loader:1055:15)
//     at Module._compile (node:internal/modules/cjs/loader:1090:27)
//     at Object.Module._extensions..js (node:internal/modules/cjs/loader:1180:10)
//     at Module.load (node:internal/modules/cjs/loader:1004:32)
//     at Function.Module._load (node:internal/modules/cjs/loader:839:12)
//     at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:81:12)
//     at node:internal/main/run_main_module:17:47

재할당 금지

const 키워드로 선언한 변수는 재할당이 금지된다.

const x = 10;
x = 20; // TypeError: Assignment to constant variable.
//     at Object.<anonymous> (c:\Users\bitcamp\git\mjs\test.js:2:3)
//     at Module._compile (node:internal/modules/cjs/loader:1126:14)
//     at Object.Module._extensions..js (node:internal/modules/cjs/loader:1180:10)
//     at Module.load (node:internal/modules/cjs/loader:1004:32)
//     at Function.Module._load (node:internal/modules/cjs/loader:839:12)
//     at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:81:12)
//     at node:internal/main/run_main_module:17:47

상수(constant)

const 키워드로 선언한 변수(variable)에 원시 값(primitive value)를 할당한 경우 변수 값을 변경할 수 없다.

이는 상수가 변수의 상대 개념이기 때문이다.

또한 일반적으로 상수의 이름은 대문자로 선언해 상수임을 명확히 나타내고, 여러 단어로 이루어진 경우에는 스네이크 케이스(snake case)로 표현하는 것이 일반적이다.

객체(object)

const 키워드로 선언된 변수에 객체를 할당한 경우 값을 변경할 수 있다.

const person = {
  name: 'jong'
};

person.name = 'Kim';

console.log(person); // {name: "Kim"}

const 키워드는 재할당을 금지할 뿐 불변(immutable)을 의미하지 않는다. 즉 새로운 값을 재할당하는 것은 불가능하지만, 프로퍼티 동적 생성, 삭제, 프로퍼티 값의 변경을 통해 객체 자체를 변경하는 것은 가능하다.


Reference

모던 자바스크립트 Deep Dive
이웅모 저 | 위키북스 | 2020년 09월 25일

0개의 댓글

관련 채용 정보