Skip to main content

Numbers in JS

Tutorial on numbers.

Doing bunch of Code Wars challenges where I had to verify if an argument is an number made me discover various ways it can be done. Below I will describe some of the things I used.

typeof operator

Basically we compare an argument to a value called 'number'. It will return for true decimals, negative numbers, math operations inside a parenthesis, infinity, NaN etc.. MDN documents going more in depth.

typeof 10 === 'number';
typeof 10.2 === 'number';
typeof (5+10) === 'number';

Number.isInteger()

We are passing a value inside the parenthesis and receive true or false depending if the valueis an integer. It will return false for decimals and math operations. MDN lists more cases.

Number.isInteger(10) === true;
Number.isInteger(10.2) === false;

NaN

There are a few ways this can be used: 
  • Number.isNaN(); method where we check if passed value is not a number. We can add  sign in front to add a negation to this evaluation and return true for numbers; 
  • isNaN(); function which is being replaced by the above method; 
  • Number.NaN(); property;
  • NaN !== 10; comparison;

I will be updating this list if I discover any new information.

Comments