Numbers in JavaScript include both integer and floating-point values.

  let integerNumber = 42;
let floatingPointNumber = 3.14;

console.log(integerNumber); // 42
console.log(floatingPointNumber); // 3.14
  

Integer

JavaScript supports several types of number literals:

  1. Decimal:

      let decimal = 42;
    console.log('Decimal:', decimal); // 42
      
  2. Binary:

      let binary = 0b101010;
    console.log('Binary:', binary); // 42
      
  3. Octal:

      
    let octal = 0o52;
    console.log('Octal:', octal); // 42
      
  4. Hexadecimal:

      let hexadecimal = 0x2A;
    console.log('Hexadecimal:', hexadecimal); // 42
      

BigInt

In JavaScript, working with very large integers (bigger than what standard Number type can accurately represent) can be done using the BigInt type. Introduced in ECMAScript 2020, BigInt allows you to handle arbitrarily large integers with precision.

Introduction to BigInt

  1. What is BigInt?

    • BigInt is a built-in object in JavaScript that provides a way to represent and operate on integers larger than 2^53 - 1, which is the maximum safe integer value for the Number type.
  2. Creating BigInt Values:

    • You can create BigInt values using the BigInt constructor or by appending n to an integer literal.

Examples

Using the BigInt Constructor

  // Creating BigInt using the constructor
let bigInt1 = BigInt(123456789012345678901234567890);
let bigInt2 = BigInt('123456789012345678901234567890');

console.log(bigInt1); // Outputs: 123456789012345678901234567890n
console.log(bigInt2); // Outputs: 123456789012345678901234567890n
  

Using Literal Syntax

  // Creating BigInt using literal syntax
let bigInt3 = 123456789012345678901234567890n;

console.log(bigInt3); // Outputs: 123456789012345678901234567890n
  

Operations with BigInt

You can perform arithmetic operations like addition, subtraction, multiplication, and division with BigInt, just like with regular numbers.

  let a = 123456789012345678901234567890n;
let b = 987654321098765432109876543210n;

let sum = a + b;
let difference = a - b;
let product = a * b;
let quotient = a / b; // Integer division, returns a BigInt

console.log(sum);        // Outputs: 1111111110111111111011111111000n
console.log(difference); // Outputs: -864197532086419753208641975320n
console.log(product);    // Outputs: 121932631112635269000000000000000n
console.log(quotient);   // Outputs: 0n
  

Important Notes

  1. No Floating-Point Support:

    • BigInt does not support floating-point operations. It is strictly for integer arithmetic.
  2. Mixing BigInt with Number:

    • You cannot mix BigInt with Number in arithmetic operations. You must convert one type to the other explicitly.
      let num = 5;
    let bigInt = 10n;
    
    // This will throw a TypeError
    // let result = num + bigInt;
    
    // Correct way
    let result = BigInt(num) + bigInt;
    console.log(result); // Outputs: 15n
      
  3. Performance Considerations:

    • While BigInt is powerful for handling large integers, it might be slower than using regular numbers for operations due to its arbitrary precision nature.

floating-point

Omitting Leading Zero

You can write decimal numbers without the leading zero, which is a valid syntax in JavaScript. For example, 0.5 can be written as .5.

      // Using leading zero
let numberWithLeadingZero = 0.75;

// Omitting leading zero
let numberWithoutLeadingZero = .75;
  

Floating-point precision issue

In computers, not just in JavaScript, 0.1 + 0.2 does not equal 0.3.

JavaScript, like many programming languages, uses floating-point arithmetic for numeric calculations. This can lead to precision issues due to the way floating-point numbers are represented in binary. Here’s an explanation and example of why calculations like 0.1 + 0.2 might not produce the expected result.

How Floating-Point Arithmetic Works

  1. Binary Representation: JavaScript uses the IEEE 754 standard for representing numbers in binary format. Many decimal fractions cannot be represented exactly in binary. For example, 0.1 and 0.2 have repeating binary representations that are approximations of their decimal values.

  2. Precision Issues: When performing arithmetic operations, these approximations can lead to small errors. For instance, the result of 0.1 + 0.2 is not exactly 0.3 in binary representation.

  3. Example: The following JavaScript code illustrates this precision issue:

      <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Floating-Point Precision Example</title>
    </head>
    <body>
        <h1>Floating-Point Precision in JavaScript</h1>
        <p id="result"></p>
    
        <script type="text/javascript">
            let sum = 0.1 + 0.2;
            let expected = 0.3;
            let result = `Sum: ${sum}, Expected: ${expected}, Equal: ${sum === expected}`;
    
            document.getElementById('result').textContent = result;
        </script>
    </body>
    </html>
      
    • Result: The code above might output something like Sum: 0.30000000000000004, Expected: 0.3, Equal: false.

Explanation

  1. Representation:

    • 0.1 and 0.2 cannot be represented exactly in binary. The closest approximation in binary results in a very small error when added.
  2. Addition:

    • When you add these approximations, the result is slightly off from 0.3.
  3. Comparison:

    • Comparing 0.1 + 0.2 directly to 0.3 returns false because the result is not exactly 0.3.

How to Handle Floating-Point Precision

  1. Rounding:

    • To avoid issues with floating-point precision, you can round the result to a fixed number of decimal places.
      let sum = 0.1 + 0.2;
    let roundedSum = Math.round(sum * 100) / 100; // Rounds to 2 decimal places
    console.log(roundedSum); // Outputs: 0.3
      
  2. Use of Libraries:

    • For precise arithmetic operations, consider using libraries like Decimal.js that handle decimal arithmetic with high precision.
      // Using Decimal.js library
    const Decimal = require('decimal.js');
    let sum = new Decimal(0.1).plus(new Decimal(0.2));
    console.log(sum.toString()); // Outputs: 0.3
      
    • To make your code work in an HTML environment and load the decimal.js library, you need to follow these steps:
    1. Download or include the decimal.js library.

    2. Write your HTML to include the library and your script. Here is a complete example:

    3. Include decimal.js Library

      You can either download the decimal.js library and include it in your project or use a CDN link.

      Option 1: Using a CDN Add the following <script> tag to your HTML to load the decimal.js library from a CDN:

        <!DOCTYPE html>
      <html lang="en">
      <head>
          <meta charset="UTF-8">
          <meta name="viewport" content="width=device-width, initial-scale=1.0">
          <title>Decimal.js Example</title>
      </head>
      <body>
          <h1>Decimal.js Example</h1>
          <p id="result"></p>
      
          <!-- Load Decimal.js from a CDN -->
          <script src="https://cdnjs.cloudflare.com/ajax/libs/decimal.js/10.3.1/decimal.min.js"></script>
          <script>
              document.addEventListener('DOMContentLoaded', function() {
                  const Decimal = window.Decimal;
                  let sum = new Decimal(0.1).plus(new Decimal(0.2));
                  document.getElementById('result').textContent = sum.toString(); // Outputs: 0.3
              });
          </script>
      </body>
      </html>
        

      Option 2: Downloading decimal.js If you prefer to download the decimal.js library and include it locally:

      Download the decimal.js library from https://github.com/MikeMcl/decimal.js and save it in your project directory (e.g., js/decimal.js).

      Include the local script in your HTML:

        <!DOCTYPE html>
      <html lang="en">
      <head>
          <meta charset="UTF-8">
          <meta name="viewport" content="width=device-width, initial-scale=1.0">
          <title>Decimal.js Example</title>
      </head>
      <body>
          <h1>Decimal.js Example</h1>
          <p id="result"></p>
      
          <!-- Load Decimal.js from a local file -->
          <script src="js/decimal.js"></script>
          <script>
              document.addEventListener('DOMContentLoaded', function() {
                  const Decimal = window.Decimal;
                  let sum = new Decimal(0.1).plus(new Decimal(0.2));
                  document.getElementById('result').textContent = sum.toString(); // Outputs: 0.3
              });
          </script>
      </body>
      </html>
        

    Explanation

    • CDN Link: In the first option, the script tag with the src attribute pointing to the CDN link loads the decimal.js library.
    • Local File: In the second option, the script tag with the src attribute pointing to the local decimal.js file loads the library.
    • DOMContentLoaded Event: The DOMContentLoaded event listener ensures that the code runs after the HTML content is fully loaded.
    • Decimal.js Usage: The Decimal object is accessed from window.Decimal (since it is added to the global window object by the library), and then used to perform the addition.

Scientific Notation

Scientific notation in JavaScript is used to represent very large or very small numbers in a compact format. JavaScript supports scientific notation for numeric values using the e or E notation, where e stands for “exponent” and E serves the same purpose.

Scientific Notation Format

In JavaScript, scientific notation follows this format:

𝑁=𝑀×10^𝐸

Where:

  • 𝑁 is the number being represented.
  • M is the base (or mantissa), which is a floating-point number.
  • E is the exponent, representing the power of 10.

Examples

Using Scientific Notation in JavaScript

Here’s how you can use scientific notation in JavaScript:

  <!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Scientific Notation in JavaScript</title>
</head>
<body>
    <h1>Scientific Notation in JavaScript</h1>
    <p id="result"></p>

    <script type="text/javascript">
        // Example of large number using scientific notation
        let largeNumber = 5.67e+10; // 5.67 * 10^10

        // Example of small number using scientific notation
        let smallNumber = 3.45e-8; // 3.45 * 10^-8

        // Display the results
        document.getElementById('result').textContent = 
            `Large number: ${largeNumber}\nSmall number: ${smallNumber}`;
    </script>
</body>
</html>
  

Explanation

  1. Large Number Example:

      let largeNumber = 5.67e+10; // This is 5.67 * 10^10, which is 56,700,000,000
      
    • The notation 5.67e+10 represents 5.67 × 10 pow 10. This is useful for expressing large numbers succinctly.
  2. Small Number Example:

      let smallNumber = 3.45e-8; // This is 3.45 * 10^-8, which is 0.0000000345
      

    The notation 3.45e-8 represents 3.45 × 10 pow −8. This is useful for expressing very small numbers in a compact form.

Using Scientific Notation for Computations

Scientific notation can be used directly in calculations:

  // Adding two numbers in scientific notation
let result = 1.23e+4 + 4.56e+3; // 12,300 + 4,560 = 16,860
console.log(result); // Outputs: 16860

// Subtracting two numbers in scientific notation
let difference = 5.67e+6 - 1.23e+5; // 5,670,000 - 123,000 = 5,547,000
console.log(difference); // Outputs: 5547000
  

Infinity

In JavaScript, Infinity is a special numeric value representing numbers beyond the maximum limit. There are two types of infinity:

  • Positive Infinity (Infinity): Represents a number greater than any other number.
  • Negative Infinity (-Infinity): Represents a number smaller than any other number.

JavaScript also has defined constants for the maximum and minimum representable numeric values:

  • Number.MAX_VALUE: The largest positive representable number, which is approximately 1.7976931348623157e+308.
  • Number.MIN_VALUE: The smallest positive representable number (closest to zero), which is approximately 5e-324.

When Does Infinity Occur?

Infinity occurs in JavaScript in several scenarios, such as:

  • Division by Zero: Dividing a non-zero number by zero results in either Infinity or -Infinity.
  • Exceeding Numeric Limits: Performing operations that exceed the maximum representable number in JavaScript results in Infinity.

Positive Infinity (Infinity)

Positive Infinity is a constant representing infinity. It can be obtained by performing operations that exceed the upper limit of the largest representable number, such as dividing a positive number by zero.

  console.log(1 / 0); // Outputs: Infinity
console.log(Math.pow(10, 1000)); // Outputs: Infinity (10 to the power of 1000)
console.log(Number.POSITIVE_INFINITY); // Outputs: Infinity
  

Negative Infinity (-Infinity)

Negative Infinity is a constant representing negative infinity. It can be obtained by performing operations that exceed the lower limit of the smallest representable number, such as dividing a negative number by zero.

  console.log(-1 / 0); // Outputs: -Infinity
console.log(-Math.pow(10, 1000)); // Outputs: -Infinity
console.log(Number.NEGATIVE_INFINITY); // Outputs: -Infinity
  

Maximum and Minimum Representable Numbers

  • Number.MAX_VALUE: This constant represents the largest positive finite value that JavaScript can represent, which is approximately 1.7976931348623157e+308.
  • Number.MIN_VALUE: This constant represents the smallest positive finite value that JavaScript can represent, which is approximately 5e-324.
  console.log(Number.MAX_VALUE); // Outputs: 1.7976931348623157e+308
console.log(Number.MIN_VALUE); // Outputs: 5e-324
  

Comparisons Involving Infinity

Infinity behaves as expected in comparisons:

  console.log(Infinity > 1000); // Outputs: true
console.log(-Infinity < -1000); // Outputs: true
console.log(Infinity === Infinity); // Outputs: true
console.log(-Infinity === -Infinity); // Outputs: true
console.log(Infinity > Number.MAX_VALUE); // Outputs: true
console.log(-Infinity < -Number.MAX_VALUE); // Outputs: true
  

Operations Involving Infinity

Arithmetic operations involving infinity follow mathematical rules:

  console.log(Infinity + 1); // Outputs: Infinity
console.log(Infinity - 1); // Outputs: Infinity
console.log(Infinity * 2); // Outputs: Infinity
console.log(Infinity / 2); // Outputs: Infinity
console.log(Infinity + Infinity); // Outputs: Infinity
console.log(-Infinity - Infinity); // Outputs: -Infinity
console.log(Infinity * -1); // Outputs: -Infinity
console.log(0 * Infinity); // Outputs: NaN (Not a Number)
console.log(Infinity / Infinity); // Outputs: NaN
  

Example in HTML with JavaScript

Here’s an example demonstrating the use of Infinity, Number.MAX_VALUE, and Number.MIN_VALUE in JavaScript within an HTML file:

  <!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>JavaScript Infinity and Numeric Limits</title>
</head>
<body>
    <h1>Understanding Infinity and Numeric Limits in JavaScript</h1>
    <p id="results"></p>

    <script type="text/javascript">
        // Examples of positive infinity
        let posInf1 = 1 / 0;
        let posInf2 = Math.pow(10, 1000);
        let posInf3 = Number.POSITIVE_INFINITY;

        // Examples of negative infinity
        let negInf1 = -1 / 0;
        let negInf2 = -Math.pow(10, 1000);
        let negInf3 = Number.NEGATIVE_INFINITY;

        // Maximum and minimum values
        let maxVal = Number.MAX_VALUE;
        let minVal = Number.MIN_VALUE;

        // Displaying results
        document.getElementById('results').textContent = `
            Positive Infinity Examples:
            1 / 0 = ${posInf1}\n
            10^1000 = ${posInf2}\n
            Number.POSITIVE_INFINITY = ${posInf3}\n
            
            Negative Infinity Examples:
            -1 / 0 = ${negInf1}\n
            -10^1000 = ${negInf2}\n
            Number.NEGATIVE_INFINITY = ${negInf3}\n
            
            Maximum and Minimum Values:
            Number.MAX_VALUE = ${maxVal}\n
            Number.MIN_VALUE = ${minVal}\n
            
            Comparisons:
            Infinity > 1000: ${Infinity > 1000}\n
            -Infinity < -1000: ${-Infinity < -1000}\n
            
            Operations:
            Infinity + 1 = ${Infinity + 1}\n
            Infinity - 1 = ${Infinity - 1}\n
            Infinity * 2 = ${Infinity * 2}\n
            Infinity / 2 = ${Infinity / 2}\n
            0 * Infinity = ${0 * Infinity}\n
            Infinity / Infinity = ${Infinity / Infinity}
        `;
    </script>
</body>
</html>
  

NaN

In JavaScript, NaN stands for “Not-a-Number.” It is a special value that indicates that a particular operation did not result in a valid number. NaN is typically the result of invalid or undefined mathematical operations.

When Does NaN Occur?

NaN can occur in several situations, such as:

  1. Invalid Mathematical Operations: Operations that do not yield a valid number.

      console.log(0 / 0); // Outputs: NaN
    console.log(Math.sqrt(-1)); // Outputs: NaN
    console.log(parseInt("abc")); // Outputs: NaN
      
  2. Operations Involving NaN: Any operation involving NaN will also result in NaN.

      let nanValue = NaN;
    console.log(nanValue + 5); // Outputs: NaN
    console.log(nanValue * 10); // Outputs: NaN
      
  3. Type Coercion Failures: When type coercion fails to convert a string to a number.

      console.log(Number("abc")); // Outputs: NaN
      

Properties of NaN

  1. Self-Inequality:NaN is unique in that it is not equal to itself.

      console.log(NaN === NaN); // Outputs: false
      
  2. Checking for NaN: Use Number.isNaN() to check if a value is NaN.

      console.log(Number.isNaN(NaN)); // Outputs: true
    console.log(Number.isNaN(123)); // Outputs: false
    console.log(Number.isNaN("abc")); // Outputs: false
    console.log(Number.isNaN(parseInt("abc"))); // Outputs: true
      

Example in HTML with JavaScript

Here’s an example demonstrating the use of NaN in JavaScript within an HTML file:

  <!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Understanding NaN in JavaScript</title>
</head>
<body>
    <h1>Understanding NaN (Not-a-Number) in JavaScript</h1>
    <p id="results"></p>

    <script type="text/javascript">
        // Examples of NaN
        let nan1 = 0 / 0;
        let nan2 = Math.sqrt(-1);
        let nan3 = parseInt("abc");

        // Checking for NaN
        let isNan1 = Number.isNaN(nan1);
        let isNan2 = Number.isNaN(123);
        let isNan3 = Number.isNaN("abc");
        let isNan4 = Number.isNaN(parseInt("abc"));

        // Displaying results
        document.getElementById('results').textContent = `
            Examples of NaN:
            0 / 0 = ${nan1}\n
            Math.sqrt(-1) = ${nan2}\n
            parseInt("abc") = ${nan3}\n
            
            Checking for NaN:
            Number.isNaN(0 / 0) = ${isNan1}\n
            Number.isNaN(123) = ${isNan2}\n
            Number.isNaN("abc") = ${isNan3}\n
            Number.isNaN(parseInt("abc")) = ${isNan4}
        `;
    </script>
</body>
</html>