Front-End/Javascript

javascript - variable types

태나미 2021. 1. 30. 22:54

1. primitive type - 더 이상 나눠질 수 없는

- 값 자체가 메모리에 저장된다

  • number
    • special numeric values
const infinity = 1 / 0; // Infinity
const netativeInfinity = -1 / 0; // -Infinity
const nAn = 'not a number' / 10; //NaN
  • string
  • boolean
    • falsy 한 값: 0, null, undefined, NaN, ''
    • truthy: 어느 값이든 있는
  • null
    • 텅텅 비어있는 empty 값, 값이 할당이 되어 있는
  • undefined
    • 선언은 되었지만, 값이 지정되어있지 않은
  • symbol
    • 동시에 다발적으로 일어날 수 있는 코드에서 우선순위를 주고 싶을 때 사용
    • 고유한 식별자를 만들 때 사용.
    • 동일한 Symbol을 작성했어도 다른 Symbol로 만들어진다.
const symbol1 = Symbol('id');
const symbol2 = Symbol('id');

console.log(symbol1 === symbol2); // false

// string 똑같다면 동일한 Symbol을 만들고 싶을 때

const gSymbol1 = Symbol.for('id');
const gSymbol2 = Symbol.for('id');

console.log(gSymbol1 === g.Symbol2); // true
console.log(`value: ${symbol1.desription}, type: ${typeof symbol1}`); // value: id, type: symbol

 

2. object type

- object는 너무커서 메모리에 올라갈 수 없음.

ellie가 포인터로 가르키고 있는 곳에 ref가 있음.

ref를 통해 object를 통해 메모리가 담겨 있는 곳을 가르킨다.

const ellie = {name: 'ellie', age: 20};
ellie.age = 29;

memory를 가르키고 있는 포인터는 잠겨있어서, 값을 재할당은 못하지만,

ellie object 안에는 name과 age 변수들이 존재.

ellie.age, ellie.name과 같이 각각 포인터가 가르키고 있는 메모리에 다른값으로 할당이 가능

 

3. function - first class function, 다른 데이터 타입처럼 변수에 할당이 가능

 

4. Javascript는 Dynamically typed language 이다.

변수 선언할 때, 어떤 타입인지 선언하지 않고, 프로그래밍이 동작할 때 할당된 값에 따라 타입이 변경될 수 있다. 

let text = 'hello';
console.log(text.charAt(0)); // h
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
console.log(text.charAt(0)); // Uncaught TypeError: text.charAt is not a function

=> 이러한 문제점 때문에, Typescript가 있는 이유

 

 

Note

Immutable data types: primitive types, frozen objects

mutable data types: all objects

 

 

출처: www.youtube.com/watch?v=OCCpGh4ujb8&list=PLv2d7VI9OotTVOL4QmPfvJWPJvkmv6h-2&index=3