Skip to content

JavaScript integer

  • by

JavaScript does not have a separate data type for integers. Instead, integers are represented using the number data type, which is used to represent both integers and floating-point numbers.

Here are some examples of integers in JavaScript:

let num1 = 100;
let num2 = -42;
let num3 = 0;

JavaScript integer example

Simple example codes perform mathematical operations with integers in JavaScript, such as addition, subtraction, multiplication, and division.

<!DOCTYPE html>
<html>
  <body>
    <script>
      let num1 = 10;
      let num2 = 5;
      let sum = num1 + num2; // sum is 15
      let difference = num1 - num2; // difference is 5
      let product = num1 * num2; // product is 50
      let quotient = num1 / num2; // quotient is 2
      
      console.log("Sum: " + sum);
      console.log("Difference: " + difference);
      console.log("Product: " + product);
      console.log("Quotient: " + quotient);
    </script>
  </body>
</html>

Output:

JavaScript integer

You can parseInt() and parseFloat() to convert strings to integers and floats, respectively.

let numString = "42";
let num = parseInt(numString); // num is 42

You can also use Math methods to perform more advanced operations.

let num = 2;
let power = Math.pow(num, 3); // power is 8
let floatNum = 3.14;
let roundedNum = Math.floor(floatNum); // roundedNum is 3

Is there an integer type in JavaScript?

Answer: In JavaScript, there is no separate integer data type. The number data type is used to represent both integers and floating-point numbers in JavaScript.

This means that when you declare a variable in JavaScript with a whole number value, it is still stored as a number data type, rather than an integer data type.

For example, if you declare a variable with a value of 5, it is stored as a number data type, as shown below:

let num = 5;
console.log(typeof num); // outputs "number"

Comment if you have any doubts or suggestions on this Js basic topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading