본문 바로가기
FRONTEND/Javascript

[Javascript] primitive type(기본 타입)

by LAY CODER 2021. 5. 1.

Varaibale(변수)

 

변수란 변할 수 있는 값을 나타내는 말이다.

 

어플리케이션을 실행하게 되면 어플리케이션 마다 쓸 수 있는 메모리가 할당되어진다.

 

let을 이용해서 myName이라는 변수를 정의하게 되면 하나의 메모리를 가르킬 수 있는 포인터가 생성된다.

 

myName이라는 변수가 가르키는 메모리 어딘가에 변수의 값이 저장된다.

 

추후 메모리에 다른 값을 변경하여 저장할 수 있다.

 

// let이라는 키워드를 이용해 myName이라는 변수를 선언하고 jasn을 할당
let myName = 'jasn';
console.log(myName); // jasn

// myName에 hello라는 새로운 값을 할당하면 myName이 가르키는 메모리에 새로운 값이 저장된다.
myName = 'hello!';
console.log(myName); // hello!

 


 

primitive type

 

 

더 이상 작은 단위로 나눠질 수 없는 단일 개체를 기본타입(primitive type) 이라고 한다.

 

값 자체가 메모리에 저장되고 데이터 자체를 변경할 수 없는 Immutable data type 이다.

 

ex) 한 번 string을 정의하게 되면 통째로 메모리에 올렸다가 다른 string으로 변경은 가능하지만

string data 자체를 변경하는 건 불가능하다.

 

종류에는 number, string, boolean, null, undefined, symbol 등이 있다.

 

 

number 

 

javascript는 값에 상관없이 숫자면 type을 number로 할당한다.

 

const count = 17;
const size = 17.1;


console.log(`value: ${count}, type : ${typeof count}`); // value: 17, type : number

console.log(`value: ${size}, type : ${typeof size}`); // value: 17.1, type : number

 

special numeric values : infinity, -infinity, NaN

 

무한대를 나타내는 숫자 infinity와 숫자가 아님을 나타내는 Nan이 있다.

 

// 양의 무한대 숫자
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

 

javascript의 최대 숫자 이상을 사용할 수 있게 해준다. (아직 크롬, 사파리만 이용 가능하다.)

 

숫자 뒤에 n을 붙여서 사용한다.

 

const bigInt = 123456768901234567890n;

// value: 123456768901234567890, type : bigint
console.log(`value: ${bigInt}, type : ${typeof bigInt}`); 

 

boolean

 

false : 0, null, undefined, NaN, ''

true : false를 제외한 모든 값은 ture

 

const test = 3 < 1;
console.lof(test) // false

 

null & undefined

 

null은 해당 변수가 empty 값이라고 지정해주는 것이고

 

undefined은 해당 변수가 선언은 되었지만 값이 아무것도 지정되어있지 않은 것이다.

 

let nothing = null; // object 타입이지만 value는 null로 비어있다.
let a;

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

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

 

 

 

symbol

 

고유한 식별자가 필요하거나 우선순위를 주고 싶을 때 사용한다.

 

Symbol.for()은 주어진 string에 맞는 심볼을 생성해 준다.

 

symbol의 value를 출력하면 error가 발생 description을 이용하여 출력해야 한다.

 

const symbol1 = Symbol('id'); // 두 가지는 서로 다른 고유한 식별자 이다.

const symbol2 = Symbol('id');

console.log(symbol1 === symbol2); // false


const symbol3 = Symbol.for('id'); // 'id'에 맞는 symbol

const symbol4 = Symbol.for('id');

console.log(symbol3 === symbol4); // true


// value: id, type : symbol
console.log(`value: ${symbol4.description}, type : ${typeof symbol4}`);

 

References


www.youtube.com/watch?v=OCCpGh4ujb8&list=PLv2d7VI9OotTVOL4QmPfvJWPJvkmv6h-2&index=3&t=186s

댓글