TIL 4 | 자바스크립트 데이터타입

Lofo·2021년 2월 15일
0

Javascript

목록 보기
11/14

Primitive data type

Primitive data type(원시 값?)은 객체가 아니면서도 메서드가 아닌 데이터입니다. 그 종류에는 number, string, boolean, bigInt, undefined, symbol이 있습니다.

number

number타입은 우리가 일반적으로 생각하는 정수, 소수 등등이 있습니다.

const count = 17; // integer
const size = 17.1; // decimal number
console.log(`value: ${count}, type: ${typeof count}`);
console.log(`value: ${size}, type: ${typeof size}`);

우리는 흔히 infinity, -infinity, Na 값들을 숫자라고 생각합니다. 하지만 이들은 자바스크립트에서 number타입의 값에 해당하지 않습니다. 이점을 유의하지 않으면 에러가 발생할 수 있습니다.

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

bigInt

bigInt는 Number타입에서 최대 정수로 설정해 놓은 값(-(2^53-1)) ~ (2^53-1)보다 더 큰 숫자를 다룰 때 사용하기 위해 만들어졌습니다. 숫자에 n만 추가하면 BigInt라고 인식합니다.

//const overInt = 123456789012345678901234567890; //에러가 발생합니다.
const bigInt = 123456789012345678901234567890n;
console.log(`value: ${bigInt}, type: ${typeof bigInt}`);
// 출력: value: 123456789012345678901234567890, type: bigInt
Number.MAX_SAFE_INTEGER; // 최대 정수값을 출력합니다.

string

string은 하나의 문자와 두 개 이상의 문자로 이루어진 문자열로 이루어진 데이터 타입입니다. string은 같은 string타입끼리의 +연산이 가능합니다.

const char = 'c'; //하나의 문자
const brendan = 'brendan'; // 두개 이상의 문자로 이루어진 문자열
const greeting = 'hello' + brendan; // string끼리의 +연산이 가능
console.log(`value: ${greeting}, type: ${typeof greeting}`);
//출력: value: hellobrendan, type: string
const helloBob = `hi ${brendan}!`; // template literals (string)
console.log(`value: ${helloBob}, type: ${typeof helloBob}`);
//출력: hi brendan!, type: string
console.log('value: ' + helloBob + ' type: ' + typeof helloBob);
//출력: value: hi brendan! type: string

boolean

boolean은 컴퓨터 내에서 참과 거짓을 나타낼 때 주로 사용됩니다. 거짓을 나타내는 false와 참을 나타내는 true가 있습니다. 타입은 다르지만 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

undefined

undefined은 변수를 선언하고 값을 할당하지 않으면 자동으로 들어가는 값입니다.

let x;
// let x = undefined; 이거랑 위의 것이랑 같은 내용이다
console.log(`value: ${x}, type: ${typeof x}`);
//출력: value: undefined, type: undefined

symbol

symbol은 가장 최근에 추가된 원시 값이라고 합니다. 유일한 식별자(unique identifier)를 만들고 싶을 때 사용합니다. 내용이 아직 어려워서 더 궁금하다면 여기를 참고해주세요.

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.description}`);
//출력: value: id, type: string
profile
Love God, Love People, Love Code.

0개의 댓글