자바스크립트의 변수 선언 방식은 const, let, var로 나눌 수 있다. 이들의 차이점은 재선언 가능여부와 스코프 특징에 따라서 달라진다.

변수 선언

1. const

const a = 'Hello';
const b = '경소고';

console.log(a) // 'Hello'
console.log(b) // '경소고';

// 재할당 불가능, 오류 발생
b = '경북소프트웨어고등학교'; // Uncaught TypeError: Assignment to constant variable.

// 초기 선언시 값을 지정안함, 오류 발생
const c; // Uncaught SyntaxError: Missing initializer in const declaration

2. let

let a = 'Hello';
let b = '경소고';

console.log(a) // 'Hello'
console.log(b) // '경소고'

b = '경북소프트웨어고등학교';

console.log(b); // '경북소프트웨어고등학교'

3. var

var a = 'Hello';
var b = '경소고';

console.log(a) // 'Hello'
console.log(b) // '경소고'

b = '경북소프트웨어고등학교';

console.log(b); // '경북소프트웨어고등학교'

자바스크립트의 스코프

자바스크립트에서의 스코프란 해당 변수에 접근할 수 있는 범위를 의미한다. 크게 블록 스코프함수 스코프로 나눌 수 있다.

1. 블록 스코프