티스토리 뷰

Language/Javascript

var, let, const

Seogineer 2021. 1. 3. 14:38

const, let은 자바스크립트 ES6(ECMA 2015)부터 생긴 구문이다.

익스플로러 호환성 문제 때문에 아직도 대다수 웹에서는 var 변수만 사용된다.

 

const

  • 선언할 때 바로 값을 넣어줘야 한다.
  • 한번 넣은 값은 바꿀 수 없는 상수이다.
const mouse_1 = '서울쥐';
mouse_1 = '귀촌쥐';	//Error

 

let

  • 선언과 값 정의를 따로 할 수 있다.
  • 넣은 값은 이후 얼마든 바꿀 수 있다.
  • 대신 선언을 다시 할 수 없다.
let mouse_2;
mouse_2 = '시골쥐';
mouse_2 = '상경쥐';

let mouse_2 = '서울쥐';	//Error

 

var

  • 값을 자유롭게 변경할 수 있다.
  • 다시 선언할 수 있다.
var mouse_3 = '청계천쥐';
mouse_3 = '잠적쥐';

var mouse_3 = '생떽쥐';

 

hoisting 차이

  • const, let 변수는 선언되기 이전에 사용하려 하면 참조 오류(Reference Error)가 발생한다.
  • var 변수는 선언되기 이전에 사용하여도 오류없이 코드가 동작한다.
console.log(mouse_1);
// ReferenceError 발생!

console.log(mouse_2);
// ReferenceError 발생!

console.log(mouse_3);
// undefined 출력

const mouse_1 = '서울쥐';
let mouse_2 = '시골쥐';
var mouse_3 = '생떽쥐';

 

scope 차이

  • let, const 변수는 블록 안에 선언되면 블록 안으로 제한되는 블록 레벨 스코프를 가진다.
  • var 변수는 함수 스코프를 가진다. 선언부가 함수 안이기만 하면 블록에 선언되었더라도 해당 함수 안을 어디든 돌아다닐 수 있다.
function house () {
	let mouse_hole = true;
    
    if(mouse_hole){
    	const mouse_1 = '서울쥐';
        let mouse_2 = '시골쥐';
        var mouse_3 = '생뗵쥐';
    }
    
    console.log(mouse_3);	// 출력 가능
}

 

참조

www.youtube.com/watch?v=HsJ4oy_jBx0

github.com/yalcodic/code-examples/blob/master/26_SCOPE/README.md

'Language > Javascript' 카테고리의 다른 글

정규표현식  (0) 2021.01.26
생성자패턴과 prototype  (0) 2021.01.17
버블링(Bubbling)과 Event delegation  (0) 2020.12.30
DOMContentLoaded 이벤트  (0) 2020.12.30
객체와 객체 탐색  (0) 2020.12.28
댓글
Total
Today
Yesterday
링크
Apple 2023 맥북 프로 14 M3, 스페이스 그레이, M3 8코어, 10코어 GPU, 512GB, 8GB, 한글