Javascript | 02. 데이터 타입, data types, let vs var, hoisting

이예림·2021년 1월 31일
0

Javascript

목록 보기
2/2
post-thumbnail

코드를 작성할 때 중요한 점
1. 데이터 전송
2. CPU에 최적화된 연산
3. 메모리의 사용을 최소화

Mutable 변수 (변경가능한)

rw (read/write) 값을 읽고 쓰는 것이 가능

let

1. ES6에 추가되어있음
2. ES6 이전 문법은 잘 사용하지 않음
3. 변수를 선언할 수 있는 명령어 딱하나 let
4. 만약 누군가 var를 쓰고 있다면,,? 쓰지말라 하십셔
    let comment = 'ellie'
    console.log(comment); // ellie
    comment = 'hello';
    console.log(comment) //hello
  • 흐름

  1. application을 실행하게 되면 application마다 쓸 수 있는 메모리가 할당됨
  2. application마다 메모리 박스가 제한적
  3. let으로 변수를 정의 할 경우 한가지의 메모리 박스를 가르키는 포인터가 생김
  4. name이라는 변수가 가리키고 있는 메모리 어딘가에 ellie가 저장되어있음
  5. ellie를 다른 값 'hello'로도 변경가능함

block scope
- 전역변수와 지역변수
- block scope를 정의하지 않으면 어디서든지 사용이 가능하다
- block scope안에 정의한 것은 안에서만 사용할 수 있음
- 밖에서 block scope안의 변수를 console로 찍으면 아무것도 안나오는 것을 확인할 수 있음
- 글로벌한 변수는 application이 실행되는 순간부터 끝날 때까지 메모리에 탑재되어있기 때문에 최소한으로 쓰는 것이 좋음
- class나 함수 if 나 for 등의 필요한 부분에서만 정의해서 쓰는 것이 좋음

    let globalName = 'global name';
    {
        let name = 'ellie'
        console.log(name); //ellie
        name = 'hello';
        console.log(name) //hello
        console.log(globalName) // global name
    }
    console.log(name); // undefined
    console.log(globalName); //global name

var

  • 쓰지말아야할 변수 할당 키워드

  • var hoisting(끌어올려줌)발생

    var hoisting이란?

    어디에 선언했는가에 상관없이 항상 제일 위로 선언을 끌어 올려주는 것

  • block scope이 없음 ⇒ block scope를 철저히 무시한다


    console.log(age) // undefined가 찍힘
    age = 4;
    var age; // file맨 위에 선언이 올라가게 됨
    console.log(age) // 4

    //block scope

    {
        age = 4;
        var age;
    }
    console.log(age) //맨위에 undefined가 찍힘

- 그래서 나온 것이 let!

Immutable 변수 (변경 불가능한)

r(read only)만 가능해서 값 변경 불가능
평소에 constant로 작성하는 것이 바람직

constant

한번 할당하면 값이 절대 바뀌지 않는 것

  • 쓰는 이유 3가지
  1. security(보안성)
  2. thread safety(다양한 thread들이 동시에 변수에 접근할 수 있는 것을 막아줌)
  3. reduce human mistakes(실수방지)
    const daysInWeek = 7;
    const maxNumber = 5;

Note

  • Immutable data와 Mutable data
    • Imutable data types: primitive types, frozen objects (i.e. object.freeze())
      • Primitive type: 언어에서 사전 정의 되어 있는 데이터 타입으로 char, byte, int 등 일반 값 타입
      • primitive type는 memory에 있는 데이터를 한번에 바꿔치기 하는 것이지 string으로 된 문자를 하나하나씩 바꿀 수는 없다
      • frozen object도 변경이 불가능
    • Mutable data types: all objects by default are mutable in JS
      • 모든 object는 스스로 변경이 가능함

Variable types (변수 타입)

어떤 프로그래밍 언어든 primitive type와 object type으로 나뉨

  1. primitive type:  더이상 작은 단위로 나누어 질 수 없는 한가지 아이템

    single item: Number, string, boolean, null, undefined, symbol

  2. Object type: primitive type을 모아 박스로 관리

    • ref ⇒ 실제로 object에 담겨있는 memory를 가르킴

    box container

  3. function type: js에서는 function도 데이터 타입처럼 변수에 할당 가능하고 함수의 parameter 인자 전달도 가능하고 return type으로도 return가능

    first-class function

  • number

C언어 자료형

  • 숫자에 대한 자료형을 하나하나 정의해줘야함
    //C언어 자료형
     int main() {
         short a = 12 //2 bytes
         int a = 12; //4 bytes
         long b = 1234; //8bytes
         float d = 1.2f // 4bytes
         double e = 8.2; //16 bytes
         return 0
    }

JS에서 숫자 정의 : number

number면 모든 것이 해결
게다가 type이 다이나믹하게 정의되기 때문에 number라고 선언하지 않아도 됨

    let count = 12;
    let size = 1.2;
    console.log(`value: ${count}, type: ${typeof count}`)
    // value: 12, type: number
    console.log(`value: ${size}, type: ${typeof size}`)
    // value: 1.2 type: number

number - special numeric vlues: infinity, -infinity, NAN :Not a number

  • 연산이 정말 valid한 연산인지 확인하는 것이 중요

    const infinity = 1 / 0;
    const negativeInfinity = -1 / 0; 
    const nAn = 'not a number' / 2; 
    console.log(infinity) // Infinity
    console.log(negativeInfinity) //-Infinity
    console.log(nAn) // NaN

Big Int

over (-253 ~ 253) 일 경우에도 수가 나오게 해줌

  • 숫자 뒤에 n만 써주면 됨
  • 최근에 추가돼서 크롬과 fire fox에서만 가능 / 사파리에선 불가능
    const bigInt = 1234567890123456789012345678901234567890n; // over (-2**53) ~ 2*53)
    console.log(`value: ${bigInt}, type: ${typeof bigInt}`);
    //value: 1234567890123456789012345678901234567890, type: bigint

String

  • 문자열 + 문자열 가능
  • '`'을 이용하면 간편하게 string을 출력할 수 있음
    // string
    const char = 'c';
    const brendan = 'brendan';
    const greeting = 'hello ' + brendan;
    console.log(`value: ${greeting}, type: ${typeof greeting}`); //value: hello brendan, type: string
    const helloBob = `hi ${brendan}!`; //template literals (string) 
    console.log(`value: ${helloBob}, type: ${typeof helloBob}`); //value: hi brendan!, type: string
    console.log('value: ' + helloBob + ' type: ' + typeof helloBob); //value: hi brendan! type: string

boolean

    // boolean
    // false: 0, null, undefined, NaN, ''
    // true: any other value
    const canRead = true;
    const test = 3 < 1; // false
    console.log(`value: ${canRead}, type: ${typeof canRead}`);
    console.log(`value: ${test}, type: ${typeof test}`);

null and undefined

  • null : null로 값이 할당 된 경우
  • undefined: 선언은 되었는데 값이 정해지지 않은 경우
    // null
    let nothing = null;
    console.log(`value: ${nothing}, type: ${typeof nothing}`);

    // undefined
    let x;
    console.log(`value: ${x}, type: ${typeof x}`);

symbol

  • map이나 다른 자료구조에서 고유한 식별자가 필요하거나 동시다발적으로 일어나는 concurrent에서 우선순위 주고 싶을 때
  • 정말 고유한 식별자 쓰고싶을 때 씀
  • Symbol : 고유한 식별자를 만들고 싶을 때
  • Symbol.for : 동일한 symbol을 만들고 싶을 때 (같냐 물었을 때 true나옴)
  • symbol을 읽기 위해선 변수.description 필수
    // symbol, create unique identifiers for objects
    const symbol1 = Symbol('id');
    const symbol2 = Symbol('id');
    console.log(symbol1 === symbol2); //false

    //동일한 symbol을 만들고 싶을 때 symbol.for
    const gSymbol1 = Symbol.for('id');
    const gSymbol2 = Symbol.for('id');
    console.log(gSymbol1 === gSymbol2); // true
    console.log(`value: ${symbol1.description}, type: ${typeof symbol1}`);

object

박스 형태로 변수 지정

  • const로 ellie를 지정했기 때문에 이는 변경 불가능 하지만 안의 변수 name과 age는 . 을 통해 변경가능함
    // object, real-life object, data structure
    const ellie = { name: 'ellie', age: 20 };
    ellie.age = 21; // 변경가능 

Dynamic Typing

js는 dynamically type language라고 불림
C나 Java는 static type language라고 부름

  • static type : 변수 선언 시 어떤 타입인지 결정해서 같이 선언함
  • dynamically type : 변수 선언시 어떤 타입인지 결정 안해도 할당된 값에 따라서 type이 변경될 수 있음
  • dynamic typed language
    • string + num 하게 될 경우 + 를 문자 합으로 이해해서 string으로 됨
    • string / string 안에 string이 num값일 경우 /를 연산으로 이해해서 type이 num으로 바뀜
    • 하지만 마지막처럼 같은 변수로 string과 변수를 계속 왔다갔다 하게 되면서 timeout이 뜨게 됨 ⇒ Type Script 가 나오게 됨
    // 5. Dynamic typing: 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

    //string + num = string
    text = '7' + 5;
    console.log(`value: ${text}, type: ${typeof text}`); //value: 75, type: string

    //string / strnig = number
    text = '8' / '2';
    console.log(`value: ${text}, type: ${typeof text}`); //value: 4, type: number
    console.log(text.charAt(0)); // time error 
profile
1년차 프린이🙊

0개의 댓글