Premium lesson

Working With Numbers in JavaScript II

JavaScript·3 min read·Feb 10, 2025

In JavaScript, beyond numeric data, the Number type is also used to represent special values like NaN, Infinity, or -Infinity.

Converting expressions to numbers

To convert a string or an expression into an integer or a floating point number, you can use the global built-in Number function:

Number(expression)

Note that if the value can't be converted into a valid number, the Number function will return NaN.

Example

In this example, all values will be converted to numbers:

Number(1)       // 1Number('123')   // 123Number(null)    // 0Number(true)    // 1Number(false)   // 0

However, these values will be converted to NaN:

Number('text')      // NaNNumber(undefined)   // NaN

Converting strings to integers

icon light bulb key

Unlock the Build CLI Apps in JavaScript & Node.js module

Learn how to build, integrate, and safeguard scalable CLI tools, scripts, and apps with JavaScript, Node.js, npm, and Git.

You get immediate access to:

  • 45 focused lessons across JavaScript, Node.js, npm, and Git
  • 17 real-world projects with commented solutions
  • Ongoing updates to this bundle
  • Lifetime access to this bundle
Unlock this module