JavaScript Number Properties

Number properties provide information about numeric limits and special values in JavaScript. Understanding these properties helps you write robust code that accounts for unusual cases like infinity or not-a-number values.

Key Topics

MAX_VALUE and MIN_VALUE

Number.MAX_VALUE returns the largest numeric value possible in JavaScript, and Number.MIN_VALUE returns the smallest positive numeric value.

console.log(Number.MAX_VALUE);
console.log(Number.MIN_VALUE);

Output

> 1.7976931348623157e+308

> 5e-324

Explanation: Number.MAX_VALUE and Number.MIN_VALUE represent the range of numbers JavaScript can handle before rounding issues occur.

Infinity and NaN

Infinity represents values larger than Number.MAX_VALUE, and NaN stands for "Not a Number" indicating an invalid numeric operation.

console.log(1 / 0);
console.log(Number("abc"));

Output

> Infinity

> NaN

Explanation: Dividing by zero returns Infinity, and attempting to convert a non-numeric string to a number returns NaN.

MAX_SAFE_INTEGER and MIN_SAFE_INTEGER

Number.MAX_SAFE_INTEGER and Number.MIN_SAFE_INTEGER define the range within which integers can be represented accurately.

console.log(Number.MAX_SAFE_INTEGER);
console.log(Number.MIN_SAFE_INTEGER);

Output

> 9007199254740991

> -9007199254740991

Explanation: Within these safe integer ranges, numbers can be accurately represented. Beyond these values, precision may be lost.

JavaScript Usage in DOM

This DOM-based example demonstrates displaying numeric limits and special values on a webpage for user reference.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Number Properties in DOM</title>
</head>
<body>
    <h1>Number Properties Demo</h1>
    <button onclick="showProperties()">Show Properties</button>
    <div id="info"></div>

    <script>
        function showProperties() {
            let content = "Max Value: " + Number.MAX_VALUE + "
" + "Min Value: " + Number.MIN_VALUE + "
" + "Max Safe Integer: " + Number.MAX_SAFE_INTEGER + "
" + "Min Safe Integer: " + Number.MIN_SAFE_INTEGER; document.getElementById("info").innerHTML = content; } </script> </body> </html>

Key Takeaways

  • Numeric Limits: Use MAX_VALUE, MIN_VALUE, MAX_SAFE_INTEGER, and MIN_SAFE_INTEGER to understand numeric boundaries.
  • Special Values: Infinity and NaN represent infinite and invalid numeric states.
  • DOM Integration: Display numeric property information to inform users or debug code.