Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
How to declare numbers in JavaScript?
JavaScript is a dynamically typed language, meaning variables can hold any data type without explicit type declaration. You can declare number variables using var, let, or const keywords.
Basic Number Declaration
Here's how you can declare numbers in JavaScript:
<html>
<body>
<script>
var points = 100;
var rank = 5;
let score = 85;
const maxLevel = 10;
console.log("Points:", points);
console.log("Rank:", rank);
console.log("Score:", score);
console.log("Max Level:", maxLevel);
</script>
</body>
</html>
Points: 100 Rank: 5 Score: 85 Max Level: 10
Different Number Types
JavaScript supports integers, floating-point numbers, and special numeric values:
<html>
<body>
<script>
// Integer numbers
var wholeNumber = 42;
var negativeNumber = -15;
// Floating-point numbers
var decimal = 3.14;
var scientific = 2.5e3; // 2500
// Special numeric values
var infinity = Infinity;
var notANumber = NaN;
console.log("Whole number:", wholeNumber);
console.log("Negative:", negativeNumber);
console.log("Decimal:", decimal);
console.log("Scientific:", scientific);
console.log("Infinity:", infinity);
console.log("NaN:", notANumber);
</script>
</body>
</html>
Whole number: 42 Negative: -15 Decimal: 3.14 Scientific: 2500 Infinity: Infinity NaN: NaN
Example: Using Numbers in Conditions
<html>
<body>
<script>
var age = 20;
var minimumAge = 18;
if (age > minimumAge) {
document.write("<b>Qualifies for driving</b>");
} else {
document.write("<b>Too young to drive</b>");
}
// Also log to console
console.log("Age:", age);
console.log("Minimum age:", minimumAge);
console.log("Qualifies:", age > minimumAge);
</script>
</body>
</html>
Variable Declaration Keywords
| Keyword | Scope | Reassignable | Hoisting |
|---|---|---|---|
var |
Function/Global | Yes | Yes |
let |
Block | Yes | No |
const |
Block | No | No |
Conclusion
JavaScript numbers can be declared using var, let, or const. The language automatically handles different numeric types including integers, decimals, and special values like Infinity and NaN.
Advertisements
