Proposta de site feita pela Genesis Innovation · conteúdo do LinkedIn de Rainier Pironi

Pular para o conteúdo
Rainier Pironi

Wiki Fundamentos

Tipos primitivos e typeof

Sete primitivos, um tipo objeto, e o typeof que mente sobre null.

JavaScript tem sete tipos primitivos: string, number, bigint, boolean, undefined, symbol e null. Todo o resto (arrays, funções, datas) é objeto. Primitivo é imutável e comparado por valor; objeto é comparado por referência.

JavaScript
console.log(typeof 'oi', typeof 42, typeof 42n, typeof true);
console.log(typeof undefined, typeof Symbol('id'));
console.log(typeof {}, typeof [], typeof function () {});

Saída

string number bigint boolean
undefined symbol
object object function

A pegadinha do null

typeof null devolve 'object', um erro histórico mantido por compatibilidade. Para testar null, compare direto. Para array, use Array.isArray.

JavaScript
console.log(typeof null);
console.log(null === null);
console.log(Array.isArray([]), Array.isArray({}));

Saída

object
true
true false

Por valor e por referência

JavaScript
let a = 'texto';
let b = a;
b += '!';
console.log(a, b);

const x = {n: 1};
const y = x;
y.n = 2;
console.log(x.n, x === y, {n: 2} === {n: 2});

Saída

texto texto!
2 true false

Fontes

Conhecimento compartilhado pela Genesis Innovation.