본문 바로가기
Javascript

var, let & const 이해하기

by F.E.D 2019. 12. 15.
  • ES6 (also known as ECMAScript 2015) has major changes over JavaScript’s syntax and brings new features that didn’t exist before.

    → ES6는 (또한 에크마2015로 알려진) 자바스크립트 문법에 있어 큰 변화를 겪고, 이전에 없던 새로운 기능들을 보여줍니다.

  • ES6 is important to learn because one reason is that, it makes JavaScript better and easier to write, and also ES6 is being used together with today’s modern web technologies like React, Node.js and so on.

    → ES6를 배우는 것은 매우 중요합니다. 그 중 한가지 이유는, 자바스크립트를 조금 더 쉽게 쓰게하고 또한, es6는 오늘날의 최신 웹 기술인 리액트와 노드 제이에스와 함께 쓰이기 때문입니다.

  • In this post, you will learn the new keywords that ES6 brings for variable declarations: let and const . But firstly, let’s explain what was wrong with var .

    → 이 포스트에서 당신은 es6가 가져온 변수 선언인 let,const에 대한 새로운 키워드를 배우게 될 것입니다. 그러나 먼저, var가 무엇이 문제인지 설명해보겠습니다.

  • What was the problem with var?

    → var 변수에 무엇이 문제가 있을까요?

  • We already had the var keyword in JS for declaring variables. So why has ES6 introduced additional keywords?

    → 우리는 이미 var 키워드를 js에 선언했습니다. 그래서 왜 es6에서 새로운 변수 키워드가 생겼을까요?

  • To understand the problem in var, first you need to understand what scope is.

    → var 에 대한 문제를 이해하기 위해서, 먼저 당신은 scope에 대해서 이해할 필요가 있습니다.

  • There are 3 types of scope in JavaScript

    → 자바스크립트에는 3가지 타입의 스코프가 존재합니다.

  • Function (Local) Scope

    → 함수 (로컬) 스코프

  • Global Scope

    → 전역 스코프

  • Block Scope (new with ES6)

    → 블록 스코프

  • var supports function & global scope, but not block scope.

    → var 변수는 함수 스코프와 글로벌 스코프를 지원하지만 블록스코프를 지원하지 않습니다.

  • Function (Local) Scope(함수 스코프)

    • When a variable is defined inside a function, it will be local only for that function and can’t be used outside:

      → 변수가 함수 내부에 정의가 되면, 함수 내부에서만 존재하고 함수 밖에서는 사용할 수 없습니다.

      function local() {
       var number = 1;
       console.log(number); // 1 gets printed
      }  
      console.log(number); // undefined
      
  • Global Scope(전역 스코프)

    • When a variable is declared outside of a function, or without the var keyword then it will become Global and will be accessible from anywhere:

      → 함수 밖에 변수가 선언되거나 var 키워드없이 변수가 선언되면 그것은 전역 변수 가 되고, 어디에서든 접근 할 수 있게 됩니다.

      var number = 1;  
      function local() {
          console.log(number); // 1 gets printed
      }  
      console.log(number); // 1 gets printed
      
  • Block Scope(블록 스코프)

    • Everything inside curly braces { }, if-else cases and for loops are block-scoped. This is the part that var doesn’t support.

      → 모든 중괄호, if-else 조건문과 for 루프들은 블록스코프로 됩니다. 이것은 var가 지원하지 않는 부분입니다.

    • Let’s define a variable (with var) inside the for loop and see what gets printed…

      → var 변수를 루프 안에 정의하고 무엇이 출력되는지 보시죠.

        for(var i = 1; i < 10; i++) {
          console.log(i);
        } 
        console.log(i);    // What do we expect here?
      

    • Everything seems fine till here. But what about the second console.log?

      → 여기까지는 모든 것이 괜찮아 보입니다. 하지만 두번째로 찍히는 콘솔에는 어떻게 나타날까요?

    • The second console.log is outside of the for loop and the local variable “i” still gets printed, whereas it supposed to be undefined.

      → 두 번째 콘솔 로그는 for 루프 외부에 있으며, 지역 변수인 i는 여전히 출력(함수 스코프에 의해) 되지만 undefined으로 간주됩니다.

    • However, if we use let or const, since they are block-scoped, this problem will be solved.

      → 하지만 만약 우리가 let 또는 const를 사용하면, 그것들은 블록 스코프로 간주되기 때문에, 이 문제는 풀릴 것입니다.

    • Redeclaration issue of var

      → var 재선언의 문제

    • Another problem with var is that it allows redeclaring the same variables again and again:

      → var의 또다른 문제점은 변수를 다시 재선언하고 재선언할 수 있다는 것입니다.

        var number = 1;   // 첫번째 변수 선언
        var number = 2;   // 같은 이름을 가진 변수에 재선언
        console.log(number); // 그리고 에러가 나지 않음
      

    • Now let’s see how ES6 deals with them…

      → 자 이제 es6가 그것들을 어떻게 처리하는지 보시죠.

  • let instead of var

    → var 대신에 let 사용

  • To prevent the problems I’ve mentioned above, let’s try again with let :

    → 위에서 언급했던 이러한 문제들을 막기 위해서, let으로 다시 시도해봅시다.

      for(let i = 0; i < 10; i++) {   // let으로 변수 선언
        console.log(i);
      }
      console.log(i); // 어떤 값이 나올 것을 기대하시나요?

  • So let supports block-scope and the second console.log returns undefined. Perfect!

    → let은 블록스코프를 지원하고, 두번째 console.log 구문은 완벽하게 undefined만을 반환합니다. 완벽해요! ( var 변수는 잘못된 값을 한번 출력했었습니다.)

  • Also, trying to redeclare a variable with let returns an error:

    → 또한, 한 변수에 재선언 시 let은 에러를 반환합니다.

  • So the let keyword:

    • can be used instead of var

      → var 대신에 사용될 수 있습니다.

    • is block-scoped

      → 블록스코프의 성질

    • doesn’t allow redeclaration, but can be reassigned later

      → 재선언을 허용하지 않지만 나중에 재할당은 될 수 있습니다.

  • Const

    • Another new keyword that ES6 brings is const.

      → 또다른 새로운 키워드인 es6의 const입니다.

    • The difference between let and const is that, once we declare a variable with const, it cannot be changed later:

      → let과 const의 차이점은 우리가 const로 변수를 한번 선언하면, 이후에 다시는 변할 수 없다는 것입니다.

  • The const keyword:

    • can also be used instead of var

      → 또한 var 대신에 사용될 수 있으며

    • must be assigned once it has declared

      → 한번만 선언되어야 하며

    • is also block-scoped like let

      → let과 같이 블록스코프이며,

    • doesn’t allow redeclaration or reassignment

      → 재선언과 재할당을 허용하지 않습니다.

  • ES6 has changed JavaScript significantly and keeps changing with ES7, ES8 and so on.

    → es6는 자바스크립트에 있어 커다란 변화를 가져왓으며 es7, es8로 계속 변화를 이어가고 있습니다.

출처 : https://itnext.io/understanding-var-let-const-in-javascript-es6-a80d6c62a5f0

'Javascript' 카테고리의 다른 글

JavaScript에서 Priavate 구현  (0) 2020.03.15
[이미지] Lazy Loading에 대한 고찰  (0) 2020.02.15
반복문 없이 반복문 하기  (0) 2019.09.14
Javscript Callback  (0) 2019.09.12
Javascript 함수가 왜 1급 객체일까?  (0) 2019.09.12

댓글