JavaScript - primitives - typy podstawowe
Rodzaje typów
W JavaScript (ES6) wyróżniamy następujące typy:
- Undefined;
- Null;
- Boolean;
- String;
- Symbol;
- Number; and
- Object.
Object
określa wszystkie obiekty, tablice (Array
) i funkcje (Function
).
null
i undefined
undefined
określa niezdefiniowaną wartość, null
jest zdefiniowane jako zamierzony brak wartości (brak referencji, wiemy, że obiekt nie istnieje).
typeof null // "object" (not "null" for legacy reasons)
typeof undefined // "undefined"
null === undefined // false
null == undefined // true
null === null // true
null == null // true
undefined === undefined // true
undefined == undefined // true
!null // true
!undefined // true
isNaN(1 + null) // false
isNaN(1 + undefined) // true
Number(null) // 0
Number(undefined) // NaN
Symbol
Mogą być użyte jako klucz właściwości obiektu. Każdy symbol jest unikalny (Symbol() === Symbol()
zwraca false
). Trzeba tutaj napomnieć, że:
- klucz właściwości (property key) to symbol lub string
- nazwa właściwości (property name) to string
Number
NaN == true // false
NaN === true // false
NaN == false // false
NaN === false // false
NaN == NaN // false
Boolean(NaN) == false // true
Rzutowanie
[] + []; // JavaScript will give you "" (which makes little sense), TypeScript will error
{} + []; // JS : 0, TS Error
[] + {}; // JS : "[object Object]", TS Error
{} + {}; // JS : "[object Object][object Object]", TS Error
"hello" - 1; // JS : NaN, TS Error