변수란 무엇일까?
결론부터 말하자면, 변수는 값이 저장된 메모리 공간에 상징적인 이름을 붙인 것이다.
<변수 이해에 필요한 컴퓨터 기초 지식>
컴퓨터는 CPU를 사용해 연산하고, 메모리를 사용해 데이터를 기억한다.
메모리(memory)란, 데이터를 저장할 수 있는 메모리 셀(memory cell)의 집합체다.
메모리 셀 하나의 크기는 1바이트(8비트)이며, 컴퓨터는 메모리 셀의 크기(=1바이트) 단위로 데이터를 저장하거나 읽어들인다.
- 각 셀은 고유의 메모리 주소(memory address)를 갖는다. 이 메모리 주소는 메모리 공간의 위치를 나타낸다.
- 컴퓨터는 모든 데이터를 2진수로 처리한다. 따라서 메모리에 저장되는 모든 데이터는 데이터의 종류(숫자, 텍스트 등)와 상관없이 모두 2진수로 저장된다.
- 자바스크립트는 개발자의 직접적인 메모리 제어를 허용하지 않는다.
값이 저장될 메모리 주소는 코드가 실행될 때 메모리의 상황에 따라 임의로 결정된다. 따라서 동일한 컴퓨터에서 동일한 코드를 실행해도 코드가 실행될 때마다 값이 저장될 메모리 주소는 변경된다.
=> 코드가 실행되기 전에는 값이 저장될 메모리 주소를 알 수 없다
프로그래밍 언어는 기억하고 싶은 값을 메모리에 저장하고, 저장된 값을 읽어 들여 재사용하기 위해 변수라는 매커니즘을 제공한다.
변수(variable)는 하나의 값을 저장하기 위해 확보한 메모리 공간 자체 또는 그 메모리 공간을 식별하기 위해 붙인 이름을 말한다.
변수 = 값의 위치를 가리키는 상징적인 이름 (값 자체가 아님!) = 값이 저장된 메모리 공간에 상징적인 이름을 붙인 것
상징적 이름인 변수는 프로그래밍 언어의 컴파일러 or 인터프리터에 의해 값이 저장된 메모리 공간의 주소로 치환되어 실행된다.
변수에 여러 개의 값을 저장하려면?
- 변수는 하나의 값을 저장하기 위한 메커니즘이다.
- 여러 개의 값을 저장하려면 여러 개의 변수를 사용하거나 배열, 객체 같은 자료구조를 사용한다.
할당(assignment): 변수에 값을 저장하는 것
참조(reference): 변수에 저장된 값을 읽어들이는 것
변수 이름을 사용해 참조를 요청하면, 자바스크립트 엔진은 변수 이름과 매핑된 메모리 주소를 통해 메모리 공간에 접근해서 저장된 값을 반환한다.
식별자(identifier)
변수 이름을 식별자(identifier)라고도 한다.
식별자 = 어떤 값을 구별해서 식별할 수 있는 고유한 이름 = 메모리 주소에 붙인 이름
식별자는 값이 아니라 메모리 주소를 기억하고 있다. 식별자로 값을 구별해서 식별한다는 것은 식별자가 기억하고 있는 메모리 주소를 통해 메모리 공간에 저장된 값에 접근할 수 있다는 의미이다.
변수뿐만 아니라, 함수, 클래스 등의 이름은 모두 식별자다.
=> 메모리 상에 존재하는 어떤 값을 식별할 수 있는 이름은 모두 식별자이다.
식별자는 네이밍 규칙을 준수해야하며, 선언(declaration)에 의해 자바스크립트 엔진에 식별자의 존재를 알린다.
변수 선언(variable declaration)
변수 선언 = 변수를 생성하는 것 = 값을 저장하기 위한 메모리 공간을 확보하고, 변수 이름과 확보된 공간의 주소를 연결해서 값을 저장할 수 있게 준비하는 것
변수를 사용하려면 반드시 선언이 필요하다.
변수를 선언할 때는 var, let, const 키워드를 사용한다.
var 키워드의 단점 중 하나는 var는 함수 레벨 스코프(function-level scope)를 지원한다는 것이다. 이로 인해 의도치 않게 전역 변수가 선언될 수 있다.
var 키워드의 단점을 보완하기 위해 ES6에서는 let과 const 키워드를 도입했다
ES6 이전 사양으로 구현된 코드는 ES6 기반의 자바스크립트 엔진에서 모두 정상적으로 동작한다.
=> ES6는 하위호환성을 유지한다.
// 변수선언
var score;
변수 선언을 하고, 아직 변수에 값을 할당하지 않았다. 값이 할당되지 않았다고 해서 메모리 공간이 비어있지는 않다.
메모리 공간에는 자바스크립트 엔진에 의해 undefined라는 값이 암묵적으로 할당되어 초기화된다.
자바스크립트 엔진은 변수선언을 2단계에 거쳐 수행한다.
1. 선언 단계: 변수 이름을 등록해서 자바스크립트 엔진에 변수의 존재를 알린다.
2. 초기화 단계: 값을 저장하기 위한 메모리 공간을 확보하고 암묵적으로 undefined를 할당해 초기화한다.
* 실행 컨텍스트(excution context)
변수 이름을 비롯한 모든 식별자는 실행 컨텍스트에 등록된다.
실행 컨텍스트란 자바스크립트 엔진이 소스코드를 평가하고 실행하기 위해 필요한 환경을 제공하고 코드의 실행 결과를 실제로 관리하는 영역이다. 자바스크립트 엔진은 실행 컨텍스트를 통해 식별자와 스코프를 관리한다.
변수 이름과 변수 값은 실행 컨텍스트 내에 키(key), 값(value) 형식인 객체로 등록되어 관리된다.
var 키워드를 사용한 변수 선언은 선언 단계와 초기화 단계가 동시에 진행된다.
선언 단계를 통해 변수 이름 score를 등록하고, 초기화 단계를 통해 score 변수에 암묵적으로 undefined를 할당해 초기화한다.
=> var 키워드로 선언한 변수는 값을 할당하지 않더라도 undefined라는 값을 가지게 된다.
변수를 포함한 모든 식별자를 사용하려면 반드시 선언이 필요하다
퀴즈
- 메모리 셀 하나의 크기는 ( ) 바이트 이다.
정답: 1
- 컴퓨터에서 동일한 코드를 실행해도 코드가 실행될 때마다 값이 저장될 메모리 주소는 변경된다. (O, X)
정답: O
값이 저장될 메모리 주소는 코드가 실행될 때 메모리의 상황에 따라 임의로 결정된다.
- 식별자는 값을 기억하고 있다. (O, X)
정답: X
식별자는 값이 아니라 메모리 주소를 기억하고 있다. 식별자로 값을 구별해서 식별한다는 것은 식별자가 기억하고 있는 메모리 주소를 통해 메모리 공간에 저장된 값에 접근할 수 있다는 의미이다.
- 변수는 ( ) 레벨 스코프이다.
정답: 함수
var 키워드의 단점 중 하나는 var는 함수 레벨 스코프(function-level scope)를 지원한다는 것이다. 이로 인해 의도치 않게 전역 변수가 선언될 수 있다.
- 변수를 선언만 하고 초기화하지 않고 참조하면 오류가 난다. (O, X)
정답: X
변수를 초기화하지 않고 선언만해도 자바스크립트 엔진은 undefined로 초기화한다.
따라서 초기화 하지 않은 변수를 참조하면 undefined 값이 참조된다.
- ( )란 자바스크립트 엔진이 소스코드를 평가하고 실행하기 위해 필요한 환경을 제공하고 코드의 실행 결과를 실제로 관리하는 영역이다. 자바스크립트 엔진은 ( ) 를 통해 식별자와 스코프를 관리한다.
정답: 실행 컨텍스트(excution context)
'JavaScript' 카테고리의 다른 글
[JavaScript] 표현식과 문 (0) | 2023.11.02 |
---|---|
[JavaScript] 변수 - 변수 호이스팅, 값의 할당, 값의 재할당, 식별자 네이밍 규칙 (0) | 2023.11.01 |
[JavaScript] 함수 - 참조에 의한 전달과 외부 상태의 변경 (2) | 2023.10.27 |
[JavaScript] 함수 - 함수 호출 (2) | 2023.10.27 |
[JavaScript] 함수 - Funtion 생성자 함수, 화살표 함수(개념만) (0) | 2023.10.27 |