Numbers are one of the most important data types in JavaScript. Whether you are building a calculator, handling prices in an e-commerce app, or validating form input, you will constantly work with numbers in JavaScript.
In JavaScript, numbers represent numeric values such as:
-
Whole numbers (e.g.,
10,-5,0) -
Decimal numbers (e.g.,
3.14,99.99)
Unlike some programming languages, JavaScript uses only one number type for both integers and decimals.
Example:
Both age and price are numbers.
Creating Numbers in Jav
Explanation:
-
No quotes are used for numbers
-
They are directly written as numeric values
Checking the Type of a Number
You can confirm that a value is a number using typeof.
Output:
number
Basic Arithmetic with Numbers
JavaScript allows you to perform all common mathematical operations.
These operations are used in:
-
Calculations
-
Financial apps
-
Games
-
Data processing
Special Number Values in JavaScript
JavaScript also has some special numeric values.
NaN (Not a Number)
Output:
Nan
This means the operation does not produce a valid number.
Infinity
Output:
Infinity
Infinity represents a value larger than any number.
Converting Strings to Numbers
User input often comes as strings, so conversion is important.
Why Numbers Are Important in JavaScript
Understanding numbers helps you:
-
Perform calculations
-
Validate user input
-
Work with APIs
-
Handle money values
-
Build real-world applications
Almost every JavaScript project depends on numeric data.
Common Mistakes Beginners Make
Using quotes around numbers
Correct way
The number data type in JavaScript is simple but extremely powerful. Once you understand how to create numbers, perform calculations, and handle special values like NaN and Infinity, you can confidently work on real-world projects.