JS - var vs let vs const
2 min readNov 21, 2018
#var
Variables declared using var
are always hoisted to the top of their scope.
console.log(j); // ReferenceError: j is not definedconsole.log(i); // undefined
var i = 0;
- j is not declared.
- var i is hoisted. Here is how the interpreter executed it:
var i;
console.log(i);
i = 0;
#var
var
’s are not block-scoped, function-scoped
var i = 0
if (true) {
var i = 1;
}console.log(i); // 1//function that 'var' defined in
function foo() {
var i = 0;
}console.log(i); // ReferenceError: i is not defined
#let
- block-scoped
- The value of a constant cannot change through reassignment, and it can’t be redeclared.
- An initializer(value 값 ) for a constant is required; that is, you must specify its value in the same statement in which it’s declared (which makes sense, given that it can’t be changed later).
- 선언된 블럭안에서만 사용가능.
- 선언과 동시에 값도 같이 정해줘야함.
- 다시 선언할 수 없다.
- 사용전용 참조를 하지만 그렇다고 변경할수 없는건 아니다. object and array
let i = 0;
if (true) {
let i = 1;
}console.log(i); // 0
- add the practicing code below.
- if x,y are declared and defined using ‘const variable’, it throws an error ‘Uncaught TypeError: Assignment to constant variable.’
let {offsetX: x, offsetY: y} = e; //destructuring//const let {offsetX: x, offsetY: y} = e; // throws an errorif(this !== e.target){
x = x + e.target.offsetLeft;
y = y + e.target.offsetTop;
}
console.log(x, y)
#wait! what is the destruct assignment?
let {offsetX: x, offsetY: y} = e; //destructuring
- equal to the code below
let x = e.offsetX, y = e.offsetY;
#const = constant
- block scoped.
- const i = 0
- 한번 선언하면 다시 선언을 할 수 가 없다.
const i = 0;
i = 1; // TypeError: Assignment to constant variable.
const
doesn’t even let you declare a variable without assigning its (constant) value!
const i; // SyntaxError: Missing initializer in const declaration
const
does allow variable mutation (only objects/arrays are mutable in JS).
#ref