[JavaScript] Primitive type

민승기·2023년 9월 23일
0

JavaScript

목록 보기
3/24
post-thumbnail

Primitive values

  • 원시값, object를 제외한 불변값.
  • 기본형 타입으로 숫자, 문자열, 불리언, null, undefined, symbol이 있다.
  • null을 제외하고 typeof연산자로 테스트가 가능하다. === null 로 확인 가능하다.
// 숫자 - num 
const num = 20;
const num2 = 22.2;
console.log(`value: ${num}, type: ${typeof num}`); // value: 20, type: number
console.log(`value: ${num2}, type: ${typeof num2}`); // value: 22.2, type: number

const infinity = 1 / 0; 
const negativeInfinity = -1 / 0; // -Infinity
const nAn = 'not a number' / 2;
console.log(infinity)	// Infinity
console.log(negativeInfinity)	// -Infinity
console.log(nAn)	// NaN

// 문자열 - String
const char = 'c';
const min = 'min';
const seungit = 'hello ' + min;
console.log(`value: ${seungit}, type: ${typeof seungit}`)
const helloBob = `hi ${min}!`;
console.log(`value: ${helloBob}, type: ${typeof helloBob}`)

// 불리언 - 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}`)	// value: true, type: boolean
console.log(`value: ${test}, type: ${typeof test}`)		// value: false, type: boolean

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

// undefined
let x; // or let x = undefined
console.log(`value: ${undifined}, type: ${typeof undifined}`)	// value: false, type: undefined

// 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(symbol1 === symbol2);	// true
// console.log(`value: ${symbol1}, type: ${typeof symbol1}`)	// error
console.log(`value: ${symbol1.description}, type: ${typeof symbol1}`)	// value: id, type: string
  																		// +.description 울 붙여 String으로 변환 뒤 사용 가능함. 

// const는 상수이기 때문에 변경이 되지 않는다. 하지만 object 내 값은 변경이 가능하다.
const introduce = {name : "seungit", age : 20};
introduce.age = 22;
console.log(introduce.age);		// 22 
profile
개발자를 꿈꾸는 늙은이👨🏻‍💻

0개의 댓글