CKTIS / JavaScript
Math.abs : valeur absolue
Math.abs convertit son argument en Number et renvoie sa valeur absolue non négative, avec un comportement défini pour zéro, NaN et les infinis.
Version : ECMAScript 1 onward; example target: Node.js 24.22.2
Syntaxe
Math.abs(x)Math.abs(x) applique ToNumber à x puis renvoie sa magnitude. Une valeur négative finie devient positive, une positive ne change pas, et -0 comme +0 donnent +0. -Infinity donne Infinity et NaN reste NaN.
La conversion compte : Math.abs("-3.5") vaut 3.5, Math.abs(null) vaut 0 et l’absence d’argument donne undefined puis NaN. Un objet peut exécuter valueOf ou toString, avec effets de bord ou exception. Symbol et BigInt provoquent TypeError lors de ToNumber.
La fonction n’est pas un constructeur et est standard depuis ECMAScript 1. Utilisez-la pour la distance à zéro ou Math.abs(a - b) ; pour une longueur multidimensionnelle, utilisez Math.hypot. Le résultat reste un Number soumis aux limites IEEE 754.
Exemples
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); }Résultat
12.5 3 0 true Infinity true true 9 true