ECMAScript2015(ES2015, ES6)와 var, let, const 구분하기

HYEONG HWAN, MUN/ 1월 31, 2018/ 미분류/ 0 comments

https://blog.lael.be/post/6707

프로그래밍 언어는 다음의 4가지 속성을 가지고 있습니다.

- Syntax(구문 구조) : 문법적으로 올바른 프로그램에 대해 정확하게 설명.
- Names(이름) : 프로그램에서의 다양한 개체에 대해 이름을 명명함. (변수명, 타입명, 함수명, 클래스명 등등)
- Types(타입) : 타입이란 값의 그룹과 값이 할 수 있는 연산에 대해서 정의합니다. 이로인해서 올바른 연산을 파악하고 타입에러를 검출할 수 있습니다.
- Semantics(의미) : 프로그램의 의미를 나타냅니다. 각 줄의 의미를 알 수 있으며 프로그램이 실행되면 변수의 변화등을 정의합니다.

언어 디자이너(Language designer)이 속성을 반드시 정의하여야 하며 프로그래머(Programmer)반드시 정해진 규칙을 따라야 합니다.


프로그래밍 언어 속성을 따르면서, 프로그래밍 언어의 상세정보(Specification)가 변경된다.

Javascript 의 경우, ECMA(European Computer Manufacturers Association) 에서 논의되고 Specification 이 결정된다.

다른 프로그래밍 언어와 동일하게 javascript 도 버전이 계속 올라가고 있으며, 브라우저에 반영되고 있다.

ES2015 는 2015년 06월에 최종 출시되었다. (http://www.ecma-international.org/ecma-262/6.0/index.html)

 

- var, let, const 비교 (var vs let vs const)

let, const 는 ES2015 에 추가된 타입(Type)이다.

var는 function-scoped type이고, letconst는 block-scoped type 이다.
다음 예시를 통해 상세 정보를 알아보자.

var는 function-scoped type이다.
변수 선언 후 재 선언이 가능하고, 값 변경도 가능하다.


var x = 1;
console.log(x); // 1

function myfunction() {
    var x = 2; // 함수 내부에서만 사용하는 변수
    console.log(x); // 2
    x = x + 1;
    console.log(x); // 3
}

myfunction(); // call

console.log(x); // 1

var x = 20;
console.log(x); // 20

let는 block-scoped type이다.
변수 선언 후 재 선언이 불가능하고, 값 변경은 가능하다.
// 애초에 var 를 안쓰고 let 만 쓰는게 좋다. 다른 프로그래밍 언어에서 변수 취급은 let 과 동일하다고 보면된다.


let y = 1;
console.log(y); // 1

function myfunction() {
    let y = 2; // 함수 내부에서만 사용하는 변수
    console.log(y); // 2
    y = y + 1;
    console.log(y); // 3
}

myfunction(); // call

console.log(y); // 1

let y = 20; // SyntaxError: Identifier 'y' has already been declared
console.log(y);

const는 block-scoped type이다.
변수 선언 후 재 선언이 불가능하고, 값 변경도 불가능하다.
// 반드시 선언할 때 값을 정의해야 한다.
// 값이 포인터 타입(Pointer Type) 일 경우, 즉 Array, Object 등일 경우 그 포인터만 변경되지 않을뿐, array data 와 object data 는 변경 가능하다.


const z = 1;
console.log(z); // 1

function myfunction() {
    const z = 2;
    console.log(z); // 2
    z = z + 1; // TypeError: Assignment to constant variable.
    console.log(z);
}

myfunction(); // call

console.log(z); // 1

let z = 20; // SyntaxError: Identifier 'z' has already been declared
console.log(z);


console.log(x); // Uncaught ReferenceError: x is not defined

function myfunction() {
    x = 2; // javascript 는 별도의 지시어가 없으면 전역 변수로 취급한다.
    console.log(x); // 2
    x = x + 1;
    console.log(x); // 3
}

myfunction(); // call

console.log(x); // 3

 

let 과 const 는 2015년부터 동작하게 된 속성이라는 것이다.

 

https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Statements/const

 

 

 

 

Leave a Comment

작성하신 댓글은 관리자의 수동 승인 후 게시됩니다.

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>
*
*