I personally didn't understand how do JS act with number, but after I learnt about it.
We have to understand what's the data types of JavaScript, and how to use them. Let me help you with it. 😄
In JS we have three data types for numbers: Number
, null
, NaN
.
I'll explain each of them and give an example for each of them.
-
Number
: The main Number data type. -
null
: intentional absence of any object value. -
NaN
: Not a Number.
Number
whether it's integer like: 1
or float like: 1.3
It is number, if there was a decimal number it'll add it, if not it'll sow up as normal integer.
console.log(5/2); // Outputs: 2.5
console.log(4/2); /// Outputs: 2
We usually use
Number()
to turn the variable to number.
NULL
Null basically is none. If you made undefended variable it'll equal null
.
And it doesn't mean that it's an empty string or 0.
let nothing; // This variable is undefined.
console.log(null == nothing); // Outputs: true
console.log(null == 0); // Outputs: false
console.log(null == ""); // Outputs: false
That happens because null
only equals the undefined variable. null
and undefined
are equal but not identical.
NaN
NaN
stands for Not a Number, and it appears if you you have a filled string and converted it to number.
let thing = "Something";
console.log(Number(thing)); // Outputs: NaN
But if you compared NaN
with other NaN
it'll return
false.
let thing = "Something";
console.log(Number(thing)); // NaN
console.log(Number(thing) == NaN); // false
Use the How to fix this?
isNaN()
method instead.let something = "Value";
console.log(isNaN(something)); // True
console.log(isNaN(Number(something))); // True
Top comments (2)
I didn't mean that null is number buddy. and I just added
null
not because it's a number, it was because people think it's equal to0
and then get confused when it doesn't equal.And thanks for clarifying those topics that I didn't cover.
I know all of those, but I wanted to explain them in simple way and examples.
So I meant to do the wrong way so I show that it's wrong and explain the right way and the reason for it as much as I could.
null
is not a number but when we set it as the value of the variable if we increased it, it'll be 1.The last one I already said in the article right here ↴
I hope you read the article carefully again. 😊