TIL 016 | JavaScript 데이터 타입

JU CHEOLJIN·2021년 7월 7일
2

JavaScript

목록 보기
3/13
post-thumbnail

JavaScript의 Primitive type에 대해서 정리해보려고 한다.

Primitive type

primitive type은 변수에 할당될 때 메모리에 직접 저장되는 데이터를 말한다. 그래서 변수에 재할당을 할 때, 메모리 영역에 직접적으로 접근하여 데이터를 변경하게 된다. string, number, boolean, null, undefined, symbol 의 6가지가 있다. primitive type이 아닌 object나 fuction은 다음에 정리할 예정이다.

string

JavaScript는 한 개의 문자열 타입을 가지고 있다. ' ', " " 의 경우에는 사용성에 차이가 없다. 다만 ' '를 사용한 경우에는 문자열 중간에 '을 추가하고 싶은 경우에는 \'을 사용해야 한다.

// string
const char = "c";
const brendan = 'brendan';
const greeting = "hello " + brendan;
console.log(`value: ${greeting}, type: ${typeof greeting}`);
const helloBob = `hi ${brendan}!`; // template literals (string)
console.log(`value: ${helloBob}, type: ${typeof helloBob}`);

console.log() 등을 사용할 때 backtick을 이용하여 작성을 하게 되면 ${}을 통해 문자열에 변수를 함께 호출할 수 있다.

number

정수, 실수 등의 숫자는 number 타입을 갖는다.

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

또한, 무한대의 수 등도 포함된다.

// special numeric value
const infinity = 1 / 0;
const negativeInfinity = -1 / 0;
const nAn = "not a number" / 2;
console.log(infinity);
console.log(negativeInfinity);
console.log(nAn);

추가로 사용할 일은 많이 없지만 bigInt 를 통해 -2의 53제곱과 2의 53제곱까지의 값 표현도 가능하다.

// over (-2**53) ~ 2*53)
const bigInt = 123456789012345678901234567890123456789n; 
console.log(`value: ${bigInt}, type: ${typeof bigInt}`);
Number.MAX_SAFE_INTEGER;

boolean

truefalse의 경우에는 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

의도적으로 비어 있는 상태를 입력하려고 할 때 사용한다.

let nothing = null;
console.log(`value: ${nothing}, type: ${typeof nothing}`);

undefined

변수를 선언은 했지만 값을 주지 않았을 때 undefined가 된다. null과의 차이점에 주의해야 한다.

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

symbol

서로 충돌되지 않는 익명의 객체 속성 키를 만들 때 사용한다.

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}`
); // symbol shold convert string

위에서 symbol1symbol2 모두 id를 키로 받았지만 서로 같지 않음을 알 수 있다. 문자와 상관 없이 충돌을 방지할 수 있다.

Dynamically typed language

JavaScript는 특이한 점이 있다. 바로, 실행되는 시점에서 자동적으로 변수의 타입을 변경한다는 점이다.

let text = "hello";
console.log(`value: ${text}, type: ${typeof text}`); //hello, string
text = 1;
console.log(`value: ${text}, type: ${typeof text}`); // 1, number
text = "7" + 5;
console.log(`value: ${text}, type: ${typeof text}`); // 75, string
text = "8" / "2";
console.log(`value: ${text}, type: ${typeof text}`); // 4, number

어떤 일이 일어났는지 보자. 처음에는 text"hello"로 선언했다. 그렇기 때문에 타입으로 string이 나온 것을 알 수 있다. 하지만 1을 재할당하자 타입이 number로 변경됐다.

그 다음 줄을 보면 문자인 "7"과 숫자인 5를 더하는 연산식을 진행하였다. 이 때 Javascript는 5를 문자열로 변경하여 75라는 결과를 출력했다. 반대로, 나누기 연산의 경우에는 문자열을 숫자로 변경하여 4라는 결과를 출력했다. 이렇게 Javascript는 동적으로 데이터 타입이 변경될 수 있다. 편리하게 느껴질 수도 있지만 예기치 않은 결과를 만들어내기도 하기 때문에 주의가 필요하다.

참고자료:
드림코딩 by 엘리

profile
사회에 도움이 되는 것은 꿈, 바로 옆의 도움이 되는 것은 평생 목표인 개발자.

0개의 댓글

관련 채용 정보