CKTIS / JavaScript
Math.abs: valore assoluto
Math.abs converte l’argomento in Number e restituisce il valore assoluto non negativo, con comportamento definito per zero, NaN e infiniti.
Versione: ECMAScript 1 onward; example target: Node.js 24.22.2
Sintassi
Math.abs(x)Math.abs(x) applica ToNumber a x e restituisce la grandezza. Un valore negativo finito diventa positivo, uno positivo non cambia e -0 e +0 producono +0. -Infinity produce Infinity e NaN resta NaN.
La conversione conta: Math.abs("-3.5") è 3.5, Math.abs(null) è 0 e senza argomento undefined produce NaN. Un oggetto può eseguire valueOf o toString, con effetti collaterali o eccezioni. Symbol e BigInt generano TypeError in ToNumber.
La funzione non è un costruttore ed è standard da ECMAScript 1. Usarla per distanza da zero o Math.abs(a - b); per lunghezza multidimensionale usare Math.hypot. Il risultato resta Number con limiti IEEE 754.
Esempi
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); }Risultato
12.5 3 0 true Infinity true true 9 true