SOOM_BLOG [숨숨 블로그]

[Javascript] data types, let vs var, hoisting (feat. 드림코딩 by 엘리) 본문

TIL/js

[Javascript] data types, let vs var, hoisting (feat. 드림코딩 by 엘리)

soomst 2022. 3. 22. 19:49

let vs var

var는 선언 하기 전에 값을 쓸 수 있다. => var 호이스팅 (호이스팅 : 어디에 선언했는지 상관없이 항상 선언을 제일 위로 끌어올려주는 것.)
또한 var는 block scope가 없다. 따라서 변수를 block에 선언해도 어디에서도 호출 할 수 있다.

let은 선언하기 전에 값을 넣으면 에러가 뜨고, block scope가 있다.

따라서 var 말고 let을 쓰자!


변수 선언 type

- Variable types :  mutable 데이터 타입

- constant type :  Immutable 데이터 타입

포인터가 잠겨있어 값을 선언함과 동시에 할당한 값을 절대 바꿀 수 없다.
constant 데이터 타입으로 코드를 작성하는 것이 더 바람직하고 좋은 습관이다.

  • for security(보안) : 값 변경 불가능하기 때문!
  • for thread safety(스레드 안전) : 스레드들이 동시에 변수에 접근하여 값을 변경 할 수 있으므로
  • for reduce human mistakes(실수 방지)
mutable  immutable
let const
RW (Read/Write) R (Read Only)

Data type

1. primitive type (원시 타입)  : 데이터의 실제 값 할당 - value 자체가 메모리에 저장된다.

  • number : over (-2**53) ~ 2**53
    • number : 0, 1, 1.2, -1.4
    • Infinity : 1/0
    • -Infinity : -1/0
    • Nan : 'not a number' / 2
  • bigInt : number+'n'
    • 선언 : const bigInt = 123455678901234567890n; (뒤에 'n'을 붙여주면 됨)
  • string
    • template literals : const hello = `h1 ${helloBob}, type: ${typeof helloBab}`;
  • boolean
    • false : 0, null. undefined, NaN, ''
    • true : any other value
  • null :  텅텅 비어있는 empty 값.
  • undefined : 선언은 되었지만 아무것도 지정되어 있지 않은 상태. (null인지도 모름)
  • symbol : 고유한 식별자를 주고 싶을 때 사용.
    • const symbol1 = Symbol('id');
      const symbol1 = Symbol('id');
      console.log(symbol1 === symbol2); --> false
    • Symbol.for('id'); : 주어진 string에 맞는 심볼을 만들어줘.
      const symbol1 = Symbol.for('id');
      const symbol1 = Symbol.for('id');
      console.log(symbol1 === symbol2); --> true
    • console.log(symbol1); --> error
      console.log(symbol1.description); --> id

💡 Dynamic typing

선언할 때 어떤 타입인지 선언하지 않고 프로그램이 동작할 때(런타임) 할당 된 값에 따라서 타입이 변경될 수 있다.

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)); // error!

이러한 문제를 해결하기 위해 typescript가 나옴.

 

2. object type : object를 가리키는 reference가 메모리에 저장된다.

(reference를 통해 실제로 object가 담겨있는 메모리를 가리키게 된다.)


참고 영상 : [드림코딩 by 앨리]- 자바스크립트 3. 데이터타입, data types, let vs var, hoisting | 프론트엔드 개발자 입문편 (JavaScript ES5+)