JavaScript Numbers Pro Tips

Rahul Kaklotar
2 min readApr 5, 2023

--

JavaScript Numbers Pro Tips

Here are some JavaScript number pro tips with brief examples:

  1. Converting a string to a number:
    You can convert a string to a number using the Number() or parseInt() functions. Number() converts the entire string to a number, while parseInt() converts only the beginning of the string until a non-numeric character is encountered.
const str = '123';
const num1 = Number(str);
const num2 = parseInt(str);

console.log(num1); // Output: 123
console.log(num2); // Output: 123

2. Checking for NaN: You can check if a value is NaN (Not a Number) using the isNaN() function. However, be aware that isNaN() also returns true for non-numeric values such as undefined, null, and true.

const num = NaN;

console.log(isNaN(num)); // Output: true
console.log(isNaN('hello')); // Output: true
console.log(isNaN(true)); // Output: true
console.log(isNaN(undefined)); // Output: true
console.log(isNaN(null)); // Output: false

3. Checking for finite numbers: You can check if a number is finite (not NaN or infinity) using the isFinite() function.

console.log(isFinite(42)); // Output: true
console.log(isFinite(NaN)); // Output: false
console.log(isFinite(Infinity)); // Output: false
console.log(isFinite(-Infinity)); // Output: false

4. Rounding a number: You can round a number using the Math.round(), Math.floor(), or Math.ceil() functions. Math.round() rounds to the nearest integer, Math.floor() rounds down to the nearest integer, and Math.ceil() rounds up to the nearest integer.

const num = 3.14159;

console.log(Math.round(num)); // Output: 3
console.log(Math.floor(num)); // Output: 3
console.log(Math.ceil(num)); // Output: 4

5. Generating random numbers: You can generate a random number between 0 and 1 using the Math.random() function. You can also generate a random number within a specified range using some simple math.

// Generate a random number between 0 and 1
const random1 = Math.random();

// Generate a random number between 1 and 10
const random2 = Math.floor(Math.random() * 10) + 1;

console.log(random1); // Output: a random number between 0 and 1
console.log(random2); // Output: a random number between 1 and 10

These are just a few JavaScript number pro tips to get you started. Numbers are an essential part of programming, so it’s important to be comfortable working with them.

--

--

Rahul Kaklotar

I'm front-end developer with 4 years of expertise in HTML, CSS, JavaScript, React. Passionate about creating user-friendly websites with a sharp eye for detail.