Photo by Sigmund on Unsplash

JavaScript Tip: How to Quickly Extract Number Inputs


Using the property is the most common way of getting the value of an input element. This property always returns a string, even when the input value is a number. As a result, when processing a number form field, we often have to use or to convert the resulting string into a number. Consider this example:

let input = document.querySelector('#numberinput').value;
console.log(typeof input); // => string
input = parseFloat(input, 10);
console.log(typeof input); // => number

Not many developers know that input elements with have an additional property that we can take advantage of to cut the / step: .

Here’s an example:

// notice the valueAsNumber at the end of the statement
let input = document.querySelector('#numberinput').valueAsNumber;
console.log(typeof input); // => number

Here, we’ve replaced with resulting in a number type. Keep in mind that if the input is empty, will return , as opposed to an empty string.

The takeaway from this short post is that when you want to store user input as a number, for example when you have a form that collects years employed or number of dependents, opt for rather than .

Where else do you think would come in handy? Let us know in the comments.



Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Faraz Kelhini

Faraz Kelhini


Faraz is a professional JavaScript developer who is passionate about promoting patterns and ideas that make web development more productive. Website: