JavaScript/Fundamentos/Tipos e Coerção
JavaScript⏱ ~2 min de leitura

Tipos e Coerção

Tipos primitivos, typeof e coerção implícita

JavaScript tem seis tipos primitivos: string, number, boolean, null, undefined, symbol e bigint. Diferente de Java, não há distinção entre inteiros e floats — tudo é number (ponto flutuante de 64 bits). O tipo de uma variável pode mudar a qualquer momento, pois JS é dinamicamente tipado.

Coerção implícita é a conversão automática de tipos que o JS faz para executar operações. O operador + com qualquer string realiza concatenação — o outro valor é convertido para string. Operações aritméticas tentam converter para number. Isso é a fonte de piadas famosas: [] + [] é "", [] + {} é "[object Object]".

Para comparações seguras, sempre use === (igualdade estrita) em vez de == (igualdade frouxa). O == faz coerção antes de comparar: 0 == "0" é true, mas 0 === "0" é false. A regra simples: use === em 100% dos casos.

Exemplo.java
// ── Tipos primitivos ─────────────────────────────
typeof "texto"    // "string"
typeof 42         // "number"
typeof 3.14       // "number" (tudo é number!)
typeof true       // "boolean"
typeof undefined  // "undefined"
typeof null       // "object" ← bug histórico da linguagem
typeof Symbol()   // "symbol"

// ── Coerção implícita (cuidado!) ──────────────────
"5" + 3        // "53"  — number vira string
"5" - 3        // 2     — string vira number
"5" * "3"      // 15    — ambas viram number
true + 1       // 2     — true vira 1
false + 1      // 1     — false vira 0
null + 1       // 1     — null vira 0
undefined + 1  // NaN   — undefined não converte

// ── == vs === ────────────────────────────────────
0 == "0"       // true  ← coerção perigosa
0 === "0"      // false ← correto!
null == undefined  // true  ← surpreendente
null === undefined // false ← correto

// ── Conversão explícita (preferida) ──────────────
Number("42")   // 42
Number("abc")  // NaN
String(42)     // "42"
Boolean(0)     // false
Boolean("")    // false  (string vazia = falsy)
Boolean("0")   // true   (string não-vazia = truthy!)
💡 Dica pro

Memorize os valores falsy: false, 0, -0, 0n, "", null, undefined, NaN. Tudo o mais é truthy — incluindo [], {} e "0". Isso é usado constantemente em condicionais.

Recompensa+25 XP+exercícios