C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
JavaScript Math abs() methodThe JavaScript math abs() method returns an absolute value of a given number. The abs() is a static method of Math. SyntaxThe abs() method is represented by the following syntax: Math.abs(num) Parameternum - A number. ReturnAn absolute value of a number. JavaScript Math abs() method exampleHere, we will understand abs() method through various examples. Example 1Let's see an example to print the absolute value of a number. <script> document.writeln(Math.abs(-4)+"<br>"); document.writeln(Math.abs(-7.8)+"<br>"); document.writeln(Math.abs('-4')); </script> Output: 4 7.8 4 Example 2Let's see some cases where abs() method returns 0. <script> document.writeln(Math.abs(null)+"<br>"); document.writeln(Math.abs([])+"<br>"); document.writeln(Math.abs('')); </script> Output: 0 0 0 Example 3Let's see some cases where abs() method returns NaN. <script> document.writeln(Math.abs("string")+"<br>"); document.writeln(Math.abs([2,3])+"<br>"); document.writeln(Math.abs()); </script> Output: NaN NaN NaN Example 4Let's understand the abs() method with your own test cases. <script> function display() { var x=document.getElementById("num").value; document.getElementById("result").innerHTML=Math.abs(x); } </script> <form> Enter a number: <input type="text" id="num"> <input type="button" onclick="display()" value="submit"> </form> <p><span id="result"></span></p>
Next TopicJavaScript Math
|