[Java Script]4. 변수 타입 (Variable types)

17806 단어 Java ScriptJava Script

이미지 출처 : http://junil-hwang.com/blog/javascript-es6-spec/

해당 포스트는 "드림코딩 엘리의 Java Script 강의" 를 토대로 이해한 내용을 정리한 내용입니다. 혹시 틀린 부분이 있을 경우 댓글 부탁드립니다.

4. 변수타입 (Variable types)

Variable types에는 크게 Primitive type (single type)Object type 으로 나눌 수 있다.

Primitive type은 더 이상 쪼갤수 없는 타입으로 number, string, boolean, null, undefined, symbol 등이 있다.

Object type은 여러가지의 primitive type을 단 box로 묶어서 관리 할수 있는 type이다.
Java Script 에서는 function 도 Variable types 중 하나이다.

Java, C언어 에서는 얼마나 큰 숫자가 들어갈 것인지를 미리 고려하여 선언하여야하지만 자바스크립트는 그럴 필요가 없다.


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

4.1. Primitive type

4.1.1. Number

special numeric values : infinity, -infinity, Na


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

infinity 는 무한대의 값이므로 "Infinity"라는 값을 출력한다.
negativeInfinity 는 마이너스 무한대의 값이므로 "-Infinity"라는 값을 출력한다.

4.1.2. String

const char = 'c';
const brendan = 'brendan';
const greeting = 'hello' + brendan;
// value : hellobrendan, type : string
console.log(`value: ${greeting}, type: ${typeof greeting}`);

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

출력방식 중, 아래 두 방식이 있다.
''가 아닌 ``를 사용하면 사이에 있는 띄어쓰기까지 같이 출력할 수 있고 +를 사용할 필요가 없어서 더 편하다. 또한 가독성 또한 좋다.


console.log(`value: ${helloBob}, type: ${typeof helloBob}`); 
console.log('value: ' + helloBob + '  type: ' + typeof helloBob);

4.1.3. Boolean

Boolean에는 True와 False 두가지가 있다.
False : 0, null, undefined, NaN, ''
Ture : 그 외 다른 값

const canRead = true;
const test = 3 < 1; 
// value : true, type : boolean
console.log(`value: ${canRead}, type: ${typeof canRead}`);
// value : false, type : boolean
console.log(`value: ${test}, type: ${typeof test}`);

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

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

4.1.4. Symbol

Sysmbol이라는 data type은 ES6에 추가되었다. Symbol은 추후에 따로 정리할 예정이니 일단 봐두자.

// symbol, create unique identifiers for objects
const symbol1 = Symbol('id');
const symbol2 = Symbol('id');
// false
console.log(symbol1 === symbol2);

const gSymbol1 = Symbol.for('id');
const gSymbol2 = Symbol.for('id');
// true
console.log(gSymbol1 === gSymbol2)
// value : id , type : string
console.log(`value: ${symbol1.description}, type: ${typeof symbol1.description}`)

좋은 웹페이지 즐겨찾기