본문 바로가기

Programming Language/Javascript

[강의노트][드림코딩] 데이터 타입

드림코딩 자바스크립트 데이터타입 강의 노트

 

1. Use strict
'use strict';

2. Variable (변수) - rw(read/write)
 - Application에는 변수를 제한적 메모리가 할당
 - 변수의 선언을 통해 일정 메모리 사용
 - 해당 메모리에 값을 변경하여 할당 가능
 - Mutable type  : "let"
 - Block scope 외부, 파일 내에는 Global scope
{
    let name = 'ellie'; // 변수 name 선언, 값 ellie 할당
console.log(name);
name = 'hello'; // hello 할당
console.log(name);
}

 - 일반적으로 선언을 하고 값을 할당하는데 var은 무시하고 선언 전에도 할당 가능
 - 이는 var hoisting(move declaration to the top) 특성 및 block scope에 제한 되지 않기 때문
 - 선언 위치와 상관없이 위로 끌어올리며, block scope을 무시하고 밖에서도 이용 가능
 - 메모리 절약을 위해 Global scope보다는 Block scope 내에서 선언 및 할당 권장

3. Constant - r(read) only
 - Immutable data type : "const"
 - 값을 선언함과 동시에 할당 후 변경 불가
 - 보안, 휴먼 에러, thread safety 등을 고려하여 사용 권장
<NOTE>
 * Immutable data type : primitive types, frozen object (i.e object.freeze())
 * Mutable data type : all object by default are mutable in JS
 * Favor immutable data type always for few reasons:
 

4. Variable types
 (1) Primitive type(single item) - 값 자체가 메모리에 저장: number, string, boolean, null, undefine, symbol etc
 (2) Objective type(box container) - 참조값이 메모리에 저장 : group of single items
 (3) function : first-class function - 변수 할당, 인자 전달, return 가능

* Number
console.log(1/0); //infinity
console.log(-1/0); //negative infinity
console.log('not a number'/2) // NaN

* String
 - templete literals  - 중간 문자열 및 공백 반영
const 변수 = 'Leo'
const helloLeo = `${변수} hello!`
console.log(helloLeo);

* Boolean
 - false == 0, null, undefined, NaN, ''
 -true == 그외 나머지

* undefined
 - 할당되지 않은 경우도 포함
let x;
console.log(x);

 * Symbol
const symbol1 = Symbol('id');
const symbol2 = Symbol('id');
console.log(symbol1 == symbol2); // false
console.log(symbol1 === symbol2); // false
 - 동일한 값을 넣어도 다른 것으로 취급, 주어지는 String에 상관 없이 고유한 식별자
 - 같은 것으로 취급하기 위해서 '.for' 활용
const symbol3 = Symbol.for('id');
const symbol4 = Symbol.for('id');
console.log(symbol3 == symbol4); // false
console.log(symbol3 === symbol4); // false
 - 직접 출력이 불가하여 '.description' 활용
console.log(`${symbol1.description}, ${typeof symbol1}`);
 - console.log(`${symbol1}, ${typeof symbol1}`); // Error

5. Dynamic typing - 런타임에서 타입이 결정되기 때문에 Error Risk
let text = 'hello';
console.log(text.charAt(0));
console.log(`value : ${text}, type :${typeof text} `);
text = 1;
console.log(`value : ${text}, type :${typeof text} `);
text = '7'+5; // String
console.log(`value : ${text}, type :${typeof text} `);
text = '8'/'2'; // Number
console.log(`value : ${text}, type :${typeof text} `);
console.log(text.charAt(0));