var만 사용됨var vs. let,constvar
let
const
var name = 'Taemin';
if (name === 'Taemin') { // 함수가 아닌 if문!
var hobbies = ['Sports', 'Cooking'] // if문은 함수가 아니기 때문에 전역변수로 설정된 것. 정상적인 전역 변수임.
console.log(hobbies);
}
function greet() {
var age = 31;
var name = 'Lee Taemin' // 외부의 변수 쉐도잉(덮어쓰기)
console.log(name, age, hobbies);
}
console.log(name, hobbies);
greet()
// 출력
// ['Sports', 'Cooking']
// Taemin ['Sports', 'Cooking']
// Lee Taemin 31 ['Sports', 'Cooking']
var name = 'Taemin';
if (name === 'Taemin') { /
let hobbies = ['Sports', 'Cooking'] // let으로 바뀜
console.log(hobbies);
}
function greet() {
var age = 31;
var name = 'Lee Taemin'
console.log(name, age, hobbies);
}
console.log(name, hobbies);
greet()
// 출력
// ['Sports', 'Cooking']
// Uncaught ReferenceError: hobbies is not defined
let, const를 사용해 중괄호(함수, if, 반복문, try~catch문 등) 안에 변수를 생성하면, 변수는 해당 블록으로 스코프가 지정되고 중괄호는 결국 블록을 표시. → 따라서 해당 블록에서만 사용 가능. 블록 밖에서는 사용 불가능.JavaScript 엔진과 브라우저에서 스크립트를 로드할 때, 전체 스크립트를 확인해서 함수를 찾은 뒤 자동으로 로드 & 등록 → 실제 사용하는 코드 아래에 함수를 작성하도록 함. → 변수에도 동일함.
console.log(userName); // undefined로 나옴
var userName = 'Max';
//=> 사실 다음과 같이 동작되는 것임. 브라우저가 보이지 않는 작업을 수행한 것.
//=> var 뿐만 아니라 let, const도 마찬가지..
var userName;
console.log(userName);
userName = 'Max';
그러나 let userName = 'Max';로 했을 때 오류가 났던 이유는 let,const가 undefined로 변수를 초기화하지 않기 때문이다.
=> 변수의 생성과정 : 선언 → 초기화 → 할당
var : 선언과 초기화가 동시에 이뤄진다. 즉, 변수를 등록 → 메모리 확보 → undefined 할당let, const : 선언과 초기화가 각각 이뤄진다. 즉, 초기화는 let이 실제로 사용되는 부분에서 이뤄짐. 따라서 초기화 이전에 변수를 불러오려고 하면 에러가 발생 → 변수를 위한 메모리 확보도 되지 않은 상태이기 때문에 참조 에러(Referrence Error) 발생 "use strict";
=> 배치된 함수에만 엄격모드가 활성화.
1. 예약어를 변수로 선언할 수 없게 만듦.
2. 변수 선언 필수.
JavaScript Engine 내부 : 메모리와 실행단계에 대한 관리가 이뤄짐.
JavaScrip는 Single Threaded이다.
Event Loop : Event Listener를 지원.
JavaScript에서의 Types/Values의 두 가지 카테고리
| Primitive Values(원시값) | Reference Values(참조값) |
|---|---|
| 문자열, 숫자, 불리언, null, undefined, Symbol | All other objects (more expensive to create) |
| 메모리에 저장(주로 스택). variable stores value itself |
메모리에 저장(Heap). variable stores a pointer (address) to location in memory |
| Copying a variable(=assign to different variable) copies the value | Copying a variable(=assign to different variable) copies the address |
원시값
참조값
let hobbies = ['Sports'];
let newHobbies = hobbies;
hobbies // ['Sports']
newHobbies // ['Sports']
hobbies.push('Cooking');
hobbies // ['Sports', 'Cooking']
newHobbies // ['Sports', 'Cooking']
// 값은 메모리 주소를 가르키고 있다!
let moreHobbies = [...hobbies];
hobbies.push('Taemin');
hobbies // ['Sports', 'Cooking', 'Taemin']
moreHobbies // ['Sports', 'Cooking']
const hobbies = ['Sports'];
hobbies.push('Cooking');
hobbies // ['Sports', 'Cooking']
// 해당 배열의 주소를 저장하는 것. const는 상수이고 따라서 주소를 바꿀 수 없다. 대신 주소 안의 배열의 값(?)은 변함.
const person = {age:30};
person // {age : 30}
person.age = 32;
person // {age : 32}
person = {age:33};
// 에러 발생! Assignment to constant variable.