2021. 6. 7. 01:25, Front-End/JavaScript
1. 데이터 타입
- Variable(변수, 변할 수 있는 값)
let (ES6에서 추가됬다)
ES6이전에는 Var를 썼다.
그냥 let만 쓰면 된다.
- Block scope
- Constant
const 자료형 일 때, 불변 데이터 유형 : primitive, 고정 된 객체 (예: object.freeze())
변경 가능한 데이터 유형 : 기본적으로 모든 객체는 JS에서 변경 가능합니다.
const 자료형을 선호하는 이유는 다음과 같다.
- security (보안)
- thread safety (스레드 안전성)
- reduce human mistakes (인간의 실수 감소)
- Variable types
// 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}`);
// speicla numeric values: infinity, -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
// string
const brendan = 'brendan';
const greeting = 'hello ' + brendan;
console.log(`value: ${greeting}, type: ${typeof greeting}`); // `${}` -> template literals (string)
// 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
let x;
// let x = undefined
console.log(`value: ${x}, type: ${typeof x}`);
// symbol
// - create unique identifiers for objects (개체에 대한 고유 식별자 생성)
const symbol1 = Symbol('id');
const symbol2 = Symbol('id');
console.log(symbol1 === symbol2); // > false : 동일한 string을 작성해도 다른 symbol로 만들어짐
// - string 이 같을떄 동일한 심볼을 만들고 싶으면..
const gSymbol1 = Symbol.for('id');
const gSymbol2 = Symbol.for('id');
console.log(gSymbol1 === gSymbol2); // > true
// console.log(`value: ${symbol1}, type: ${typeof symbol1}`); // > error
console.log(`value: ${symbol1.description}, type: ${typeof symbol1.description}`);
메모리에 값이 저장되는 방법은 2가지!
primitive 타입은 값 자체를 저장
object타입은 레퍼런스(주소)가 저장된다.
자바스크립트는 알아서 생각해서 값을 출력한다
'7' + 5를 보면 '7' 문자와 문자를 붙이는 줄 생각해 75로 나오고 타입도 String이 됬다
'8' / '2'는 가운데에 /가 있어 8/2를 생각해 4를 출력한다. 그리고 타입이 number가 됬다
편할수도 있지만 헷갈리고 어떤 타입인지 모를 수 있기 때문에
런타임에서 타입을 정해질때 에러가 많이 발생하는데 이것 때문에 TypeScript가 나왔다.
'Front-End > JavaScript' 카테고리의 다른 글
[JavaScript] 4_X. 클래스,객체,인스턴스 (0) | 2021.06.13 |
---|---|
[JavaScript] 4. 클래스 (0) | 2021.06.13 |
[JavaScript] 3. 함수 (1) | 2021.06.13 |
[JavaScript] 1. 콘솔출력과 async 그리고 defer (2) | 2021.06.07 |
[JavaScript] 0. 첫걸음에 대한 준비 (0) | 2021.06.06 |
Comments, Trackbacks