Math Constants

JavaScript provides 8 mathematical constants that can be accessed with the Math object:

  Math.e       // returns Euler's number (approx. 2.718)
  Math.pi      // returns PI (approx. 3.14)
  Math.sqrt2   // returns the square root of 2 (approx. 1.414)
  Math.sqrt1_2 // returns the square root of 1/2 (approx. 0.707)
  Math.ln2     // returns the natural logarithm of 2 (approx. 0.693)
  Math.ln10    // returns the natural logarithm of 10 (approx. 2.302)
  Math.log2e   // returns base 2 logarithm of E (approx. 1.442)
  Math.log10e  // returns base 10 logarithm of E (approx. 0.434)

HTML file: Displayed by browser:
<body>
<p>Math constants are E, PI, SQR2, SQR1_2, LN2, LN10, LOG2E, LOG10E:<p>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
<script>
function myFunction() {
    document.getElementById("demo").innerHTML =
    Math.E + "<br />" +
    Math.PI + "<br />" +
    Math.SQRT2 + "<br />" +
    Math.SQRT1_2 + "<br />" +
    Math.LN2 + "<br />" +
    Math.LN10 + "<br />" +
    Math.LOG2E + "<br />" +
    Math.LOG10E;
}
</script>
</body>

Math constants are E, PI, SQR2, SQR1_2, LN2, LN10, LOG2E, LOG10E:


Good habit You must use capital letters after "Math." in JavaScript. This was really puzzling for me, because the browser returns "undefined" for every one of these, if I use lowercase. Yet, at the school, on their practise pages, I had to use lowercase to get the Math objects to work at all.
Back Table of Contents Next