Repozytorium Web Developera

Archiwum z lat 2013-2018, treści mogą być nieaktualne.

JavaScript - primitives - typy podstawowe

Rodzaje typów

W JavaScript (ES6) wyróżniamy następujące typy:

  1. Undefined;
  2. Null;
  3. Boolean;
  4. String;
  5. Symbol;
  6. Number; and
  7. Object.
Sześć (6) pierwszych to typy podstawowe (primitives), natomiast 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