--- title: Math.abs() slug: Web/JavaScript/Reference/Global_Objects/Math/abs tags: - JavaScript - Math - Méthode - Reference translation_of: Web/JavaScript/Reference/Global_Objects/Math/abs original_slug: Web/JavaScript/Reference/Objets_globaux/Math/abs ---
La fonction Math.abs() retourne la valeur absolue d'un nombre, c'est-à-dire
Le code source de cet exemple interactif est disponible dans un dépôt GitHub. Si vous souhaitez contribuez à ces exemples, n'hésitez pas à cloner https://github.com/mdn/interactive-examples et à envoyer une pull request !
Math.abs(x);
xLa valeur absolue du nombre passé en argument.
abs est une méthode statique de l'objet Math et doit toujours être utilisée avec la syntaxe Math.abs().
Math.abs()Si la méthode est utilisée avec une chaîne de caractères non numérique, avec un tableau à plus d'un élément, sans paramètre ou avec {{jsxref("undefined")}}, la valeur retournée sera {{jsxref("NaN")}}. Si elle est utilisée avec {{jsxref("null")}}, la fonction renverra 0.
Math.abs('-1'); // 1
Math.abs(-2); // 2
Math.abs(null); // 0
Math.abs(''); // 0
Math.abs([]); // 0
Math.abs([2]); // 2
Math.abs([1,2]); // NaN
Math.abs({}); // NaN
Math.abs("string"); // NaN
Math.abs(); // NaN
| Spécification | État | Commentaires |
|---|---|---|
| {{SpecName('ES1')}} | {{Spec2('ES1')}} | Définition initiale. Implémentée avec JavaScript 1.0. |
| {{SpecName('ES5.1', '#sec-15.8.2.1', 'Math.abs')}} | {{Spec2('ES5.1')}} | |
| {{SpecName('ES6', '#sec-math.abs', 'Math.abs')}} | {{Spec2('ES6')}} | |
| {{SpecName('ESDraft', '#sec-math.abs', 'Math.abs')}} | {{Spec2('ESDraft')}} |
{{Compat("javascript.builtins.Math.abs")}}