2 분 소요

💎 Data Type

Mutable Data Type - let, rw(read/write)

let은 변수 선언시에 사용한다.

더이상 Var 타입을 사용하면 안되는 이유

1. Var hoisting

age = 4;
var age;
console.log(age);

위 코드에서 변수를 선언하기도 전에 할당했지만, 에러없이 4를 출력한다.
이것은 let 타입에서는 해당되지 않는 var 타입의 특성이다.
따라서 var 타입 사용을 지양해야한다.

hoisting이란?
어디에 선언했냐에 상관없이 항상 제일 위로 선언을 끌어올려주는 것을 말한다.

2. block scope를 무시한다.

{
var age;
age = 4;
}
console.log(age);

var로 선언된 age는 block 안에서 선언된 변수이지만 block scope를 무시하고 block 밖에서 출력이 가능하다.

Immutable Data Type - Constant, r(read)

constants: 한번 할당하면 값이 절대로 바뀌지 않음

  • immutable data type의 장점
    1. security: 보안상의 이유
      한번 작성한 값을 해커들이 코드를 삽입하여 변경할 수 없도록
    2. thread safety
      여러 개의 쓰레드들이 동시에 값을 변경할 수 없도록
    3. reduce human mistakes
      나 혹은 다른 개발자가 나중에 코드를 변경할 때 실수를 예방할 수 있도록

primitive type: 더이상 작은 단위로 나뉘어지지 않는 single item

값 자체가 메모리에 저장됨

  • number
    • const infinity = 1 / 0;
    • const negativeInfinity = -1 / 0;
    • const nAn = ‘not a number’ / 2;
  • string
    • template literals: string 출력 시 ${} 형태로 변수에 할당된 값을 출력하는 것
  • boolean
  • null
    let nothing = null; // null: 명확하게 empty라는 값을 지정
    console.log(`value: ${nothing}, type: ${typeof nothing}`);
    
  • undefined
    let x; // undefined: 선언은 되었지만 값을 지정하지 않음
    console.log(`value: ${x}, type: ${typeof x}`);
    
  • symbol
    • map이나 다른 자료구조에서 고유한 식별자가 필요할 때 사용
    • 혹은 동시다발적으로(concurrently) 실행될 수 있는 코드에서 우선순위 부여할 때 사용
      const s1 = Symbol('id');
      const s2 = Symbol('id');
      console.log(s1 === s2); // false
      

      => 주어지는 string에 상관없이 고유한 식별자를 만들 때 사용

      const s3 = Symbol.for('id');
      const s4 = Symbol.for('id');
      console.log(s3 === s4); // true
      

      => string이 같다면 동일한 symbol로 반들고 싶다면, Symbol.for 사용

      console.log(`value: ${s1.description}, type: ${typeof s1}`); 
      

      => symbol 출력시에는 .description 사용

      objective type: single item들을 묶어서 한 박스로 관리해 주는 것 (box container)

      primitive type과 달리, 너무 커서 한번에 메모리에 다 올라갈 수 없음
      reference를 통해 object가 담겨있는 메모리를 가리킴

  • function
  • first-class function
    • function도 다른 data type처럼 할당 가능
    • 함수의 파라미터로 전달 가능
    • 함수의 리턴타입으로 사용 가능
      const person = {name: 'ann', age: '20'};
      person.age = 21;
      
      💡 primitive type은 value로 값이 저장되고
      objective tpye은 object가 가리키는 reference가 메모리에 저장된다.
      

💎 Dynamic typing

statically typed language: C, Java
dynamically typed language: JavaScript
Dynamic typing이란 변수를 선언할 때 타입을 같이 선언하지 않고, 런타임에(프로그램이 동작할 때) 할당된 값에 따라 타입이 자동으로 결정되는 것을 뜻함

let text = 'hello';
console.log(`value: ${text}, type: ${typeof text}`); // value: hello, type: string
text = 1;
console.log(`value: ${text}, type: ${typeof text}`); // value: 1, type: number
text = '7' + 5;
console.log(`value: ${text}, type: ${typeof text}`); // value: 75, type: string
text = '8' / '2';
console.log(`value: ${text}, type: ${typeof text}`); // value: 4, type: number

하지만, dynamic typing으로 인해 위험한 상황이 연출될 수 있다.

let text = 'hello';
console.log(text.charAt(0)); // h
text = 1;
text = '7' + 5;
text = '8' / '2';
console.log(text.charAt(0)); // 현재는 string 타입이 아니기 때문에 Error 발생!

런타임에 타입이 정해지기 때문에 runtime error가 자주 발생함!
-> Dynamic typing때문에 발생하는 런타임 에러를 TypeScript에서 해결

📁 참고

DreamCoding



💛 개인 공부 기록용 블로그입니다. 👻

맨 위로 이동하기