Base de conhecimentoCentro de Exames
PT · PTPortuguês (Portugal)
Escolher idioma13

CKTIS / JavaScript

Math.abs: valor absoluto

Math.abs converte o argumento para Number e devolve o valor absoluto não negativo, com comportamento definido para zero, NaN e infinitos.

Versão: ECMAScript 1 onward; example target: Node.js 24.22.2

Sintaxe

Math.abs(x)

Math.abs(x) aplica ToNumber a x e devolve a magnitude. Um valor negativo finito torna-se positivo, um positivo não muda e -0 e +0 produzem +0. -Infinity produz Infinity e NaN continua NaN.

A conversão importa: Math.abs("-3.5") é 3.5, Math.abs(null) é 0 e sem argumento undefined produz NaN. Um objeto pode executar valueOf ou toString, com efeitos laterais ou exceção. Symbol e BigInt lançam TypeError em ToNumber.

A função não é construtor e é padrão desde ECMAScript 1. Use-a para distância de zero ou Math.abs(a - b); para comprimento multidimensional use Math.hypot. O resultado continua Number com limites IEEE 754.

Exemplos

console.log(Math.abs(-12.5), Math.abs("-3"), Math.abs(null));
console.log(Object.is(Math.abs(-0), 0), Math.abs(-Infinity));
console.log(Number.isNaN(Math.abs()), Number.isNaN(Math.abs("not-number")));
const reading = { valueOf() { return -9; } };
console.log(Math.abs(reading));
try { Math.abs(1n); } catch (error) { console.log(error instanceof TypeError); }

Resultado

12.5 3 0
true Infinity
true true
9
true

Fontes