JavaScript Numbers
Numbers in JavaScript represent both integers and floating-point values. Unlike many other languages, JavaScript does not differentiate between integer and decimal types. Mastering numbers is essential for calculations, comparisons, and data manipulation.
Key Topics
Integers and Floats
In JavaScript, numbers can be written with or without decimals. Both integers and floating-point values share the same Number type.
let intNum = 42;
let floatNum = 3.14;
console.log("Integer:", intNum);
console.log("Float:", floatNum);
Output
> Integer: 42
> Float: 3.14
Explanation: Both 42
and 3.14
are considered numbers in JavaScript, even though one is an integer and the other a decimal.
Floating-Point Precision
JavaScript uses double-precision floating-point format, which can lead to rounding issues when dealing with very large or very small numbers.
console.log(0.1 + 0.2);
Output
> 0.30000000000000004
Explanation: Due to floating-point precision, 0.1 + 0.2
does not equal exactly 0.3
, but a slightly off value.
typeof Number
The typeof
operator returns "number"
for all numeric values, making it easy to check if a variable holds a numeric value.
let value = 100;
console.log(typeof value);
Output
> number
Explanation: The typeof
operator confirms that value
is a number.
JavaScript Usage in DOM
This DOM-based example shows how to perform numeric calculations and display the result on a webpage.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Numbers in DOM</title>
</head>
<body>
<h1>Number Demo</h1>
<button onclick="calculate()">Calculate</button>
<p id="result"></p>
<script>
function calculate() {
let a = 10;
let b = 2;
let sum = a + b;
document.getElementById("result").textContent = "Sum: " + sum;
}
</script>
</body>
</html>
Key Takeaways
- Single Number Type: JavaScript uses one type for both integers and floats.
- Floating-Point Precision: Be aware of rounding errors in calculations.
- typeof: Use
typeof
to identify numeric variables. - DOM Integration: Perform calculations and update webpage content dynamically.