var, const, let

d·2020년 5월 21일
0

1. var

var의 scope은 function단위
변수를 지정함.

scope 미국식 [skoʊp] 발음듣기 영국식 [skəʊp] 발음듣기 중요도 별점 1개 다른 뜻(3건) 예문보기
1. (무엇을 하거나 이룰 수 있는) 기회 2. (주제조직활동 등이 다루는) 범위

ar hello='hello!'
function sayHello() {
var hello='hello in function!';
console.log(hello);
}

sayHello(); // hello in function!
console.log(hello); // hello!

이처럼, 'hello'라는 변수의 유효볌위가 function이라는 것을 알 수 있다.

var는 {} 단위의 scope이 아닌 function단위의 scope을 가진다.

var hello='hello';
if(true) {
var hello = 'hello in if';
}

console.log(hello); // hello in if

if절 내부에 hello 변수를 선언하였으나
var로 선언한 변수의 scope은 {}가 아닌 function이다.
따라서, hello 변수 {}바깥에서도 변경되는 것을 볼 수 있다.

***같은 변수를 두번 선언 가능하다***
var world = 'first hello';
var world = 'second hello';

console.log(world); // world가 두번 콘솔에 출력된다. 오류가 나지 않고 동작함.
그런데, 이런식의 유연한 변수 선언 방식은 오류를 발생시키도 하기 때문에 let, const를 씀

const

상수를 선언한다.
constance의 약자
상수를 한번 선언하면 반복해서 쓸 수 없다.

const hello='hello';
hello = 'change hello'; // error

상수로 선언한 hello의 값을 변경하려고 하니 오류가 나온다.

const의 scope은 {}블록이다.

const hello='hello!';
{
const hello='inner hello!';
console.log(hello); // inner hello!
}
console.log(hello); // hello!

중괄호 바깥에 const hello로 상수값이 정해져있다.
그런데 중괄호 안에서도 const hello 입력 시 오류가 나지 않는다. 이유는 const의 scope이 중괄호{}안에 있기 때문이다.

let

let도 변수를 선언한다.
let으로 선언하면 값을 재정의 할 수 있다. 반복해서 사용가능하다.

let hello = 'first hello'; // first hello
hello = 'changed hello'; // changed hello

let의 scope도 중괄호{}이다.

const와 마찬가지 scope은 괄호 변수다.
let hello='first hello';
{
let hello = 'inner hello';
console.log(hello); // inner hello
}
console.log(hello); // first hello

let hello가 중괄호 바깥에서 지정되어있는데,
scope이 {}이기 때문에 {}안에서 let hello가 다시 지정가능하다.

let은 변수를 두번 선언하지 못한다.
예를 들어서,

let hello='first hello';
let hello='second hello'; // error

var보다는 const와 let을 사용해서 명확한 코드를 만들어야 한다.

profile
d

0개의 댓글