Number Data Types in JavaScript

JavaScript2 min read
Number Data Types in JavaScript
javascriptnumber data typedata types

In JavaScript, there are 5 types of primitive data types. The first and most commonly used is the Number type.

Primitive Data Types in JavaScript: Number

In JavaScript, there are 5 types of primitive data types. The first and most commonly used is the Number type.

1. Number Type

  • The number type in JavaScript defines numeric values, which can include integers, floating-point numbers, and even binary numbers.
  • JavaScript allows performing all mathematical operations using numbers.
  • Example: Basic Arithmetic Operations
let a = 10; let b = 20; // Add two numbers and display the result document.write("a + b = " + (a + b)); // Output: "a + b = 30"

Explanation:

  • Here, a and b are initialized as numbers (10 and 20).
  • The addition operation (a + b) results in 30, which is displayed using document.write().

2. Comparison Operators

  • Numbers can be compared using comparison operators such as:
    • Greater than (>),
    • Less than (<),
    • Equal to (==),
    • Not equal to (!=).
  • These operators return boolean values (true or false) based on the result of the comparison.
  • Example: Using Comparison Operators
let x = 15; let y = 25; document.write(x > y); // Output: "false" document.write(x < y); // Output: "true" document.write(x == y); // Output: "false" document.write(x != y); // Output: "true"

Explanation:

  • The comparison x > y checks if x is greater than y, returning false since 15 is less than 25.
  • Similarly, the other comparison operations return boolean values based on the given conditions.

3. NaN (Not-a-Number)

  • JavaScript has a special numeric value called NaN (Not-a-Number), which represents an operation result that is mathematically undefined or cannot be represented as a valid number.
  • Example: NaN in Action
let result = "hello" * 10; document.write(result); // Output: "NaN"

Explanation:

  • Here, multiplying a string ("hello") by a number (10) results in NaN because this operation is undefined in JavaScript.

Summary:

  • The number type supports all mathematical operations.
  • Comparison operators return boolean values based on number comparisons.
  • NaN represents undefined or invalid numerical operations.