기타 언어/JavaScript
[JavaScript] Data type 데이터 타입
all_sound
2022. 7. 27. 10:25
JavaScript의 데이터 타입은 크게 Primitive type, Object type 두 카테고리로 나눌 수 있다.
1. Primitive Type
: 하나의 아이템을 나타낼 때 쓰인다.
: number, string, boolean, null, undefined, symbol
- Number
const count = 17; //integer 정수
const size = 17.1; //decimal 소수
console.log(`value: ${count}, type: ${typeof count}`); //value: 17, type: number
console.log(`value: ${size}, type: ${typeof size}`); //value: 17.1, type: number
const infinity = 1/0;
const negativeInfinity = -1/0;
const nAn = 'not a number'/0;
console.log(infinity); //infinity
console.log(negativeInfinity); //-infinity
console.log(nAn); //NaN (Not a number)
- String
const char = 'c';
const brendan = 'brendan';
const greeting = 'hello'+brendan;
console.log(`value: ${greeting}, type: ${typeof greeting}`); //value: hellobrendan, type: string
const helloBob = `hi ${brendan}!`; //'hi'+brendan 과 같은 표현!
console.log(`value: ${helloBob}, type :${typeof helloBob}`); //value: hi brendan!, type :string
- Boolean
false : 0, null, undefined, NaN, ' '
true : 그 이외의 다른 모든 타입들
const canRead = true;
const test = 3 < 1; //false
console.log(`value: ${canRead}, type: ${typeof canRead}`); //value: true, type: boolean
console.log(`value: ${test}, type: ${typeof test}`); //value: false, type: boolean
- Null
: 텅텅 비어있다는 뜻 = nothing, empty, unknown
let nothing = null;
console.log(`value: ${nothing}, type: ${typeof nothing}`); //value: null, type: object
- Undefined
a variable has been declared, but has not been assigned a value.
선언은 되었지만 할당이 되지 않은 값
let x;
console.log(`value: ${x}, type: ${typeof x}`); //value: undefined, type: undefined
- Symbol
object를 위한 고유의 식별자를 만들 때 사용
//symbol, create unique identifiers for objects
const symbol1= Symbol('id');
const symbol2= Symbol('id');
console.log(symbol1===symbol2); //false
const gSymbol1= Symbol.for('id');
const gSymbol2= Symbol.for('id');
console.log(gSymbol1===gSymbol2); //true
console.log(`value: ${symbol1.description}, type: ${typeof symbol1}`); //value: id, type: symbol
2. Object Type
: 말 그대로 object 형태를 갖춘 모든 타입을 말한다. 이 내용은 너무 길기 때문에 다음 기회에...
const dasol = {name: 'dasol', age: 30};
dasol.age = 21;
✔ Dynamic typing
자바스크립트는 dynamically typed language!!
type이 완전히 고정돼 있는 게 아니라, 런타임에서 다이나믹하게 정해진다.
그래서 아래와 같은 혼란스러운 상황들이 벌어진다.
문자와 숫자가 나누어 지고, 문자와 문자가 나누어 진다고???!!!
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'; //4
console.log(`value: ${text}, type: ${typeof text}`); //value: 4, type: number
규모 있고 복잡한 프로젝트를 할 때는 이러한 변동성이 큰 문제를 일으키기도 한다.