본문 바로가기
Web/JavaScript

[TypeScript] Variable Declaration (var, let, const)

by llHoYall 2020. 10. 15.

var Declarations

Declaring a variable in JavaScript has always traditionally been done with the var keyword. (ES5)

var num = 7;

Scoping Rules

It is not an error to declare the same variable multiple times with var.

var num = 7;
var num = 3;

let Declarations

let differs from var in point of semantics.

let say = "Hello";

Block Scoping

Unlike variables declared with var whose scopes leak out to their containing function, block-scoped variables are not visible outside of their nearest containing block or for-loop.

function test(param: boolean) {
  let outerNum = 7;
  
  if (param) {
    let innerNum = outerNum + 1;  // Can refer 'outerNum' from inner block
    return innerNum;
  }
  
  return innerNum;  // Can't refer 'innerNum' from outer block
}

Block-scoped variables are that they can't be read or written to before they're actually declared.

ar of JavaScript allows it by hoisting.

++num;  // Error: variable is used before being assigned.
let num = 7;

Re-declarations and Shadowing

With var declarations, I mentioned that it didn't matter how many times you declared your variables.

However, let declarations doesn't allow it.

The act of introducing a new name in a more nested scope is called shadowing.

(function shadowing(): void {
  for (let i = 0; i < 3; ++i) {
    console.log(`Outer loop i: ${i}`)
    for (let i = 0; i < 3; ++i) {
      console.log(`Inner loop i: ${i}`)
    }
  }
})()

const Declarations

const is like let declarations but, as their name implies, their value cannot be changed once they are bound.

const num = 7;
num = 3;  // Error: Cannot assign to this variable becuase it is a constant.

You should not be confused with the idea that the values const variables refer to are immutable.

Unless you take specific measures to avoid it, the internal state of a const variable is still modifiable.

const person = {
  name: 'hoya',
  age: 18
};

// Error
person = {
  name: 'kim',
  age: 30
};

// OK
person.name = 'kim';
person.age = 27;

Reading Together

2020/09/03 - [Web/JavaScript] - [JavaScript] Variable

댓글