Sobes.tech
Junior

What is the valueAsNumber property?

sobes.tech AI

Answer from AI

The property valueAsNumber provides the value of an input or option element as a floating-point number. It is useful for numeric input fields (type="number", type="range") or for obtaining the numeric value from the value attribute of an option element.

// Getting the numeric value from an input of type="number"
const inputNumber = document.getElementById('myNumberInput');
const numberValue = inputNumber.valueAsNumber;
console.log(typeof numberValue); // Will output 'number'

// Getting the numeric value from an option
const selectElement = document.getElementById('mySelect');
const selectedOption = selectElement.options[selectElement.selectedIndex];
const optionNumberValue = selectedOption.valueAsNumber;
console.log(typeof optionNumberValue); // Will output 'number'

If the element does not have a numeric value, valueAsNumber will return NaN. This can happen for non-numeric input types or if the value cannot be converted to a number.

Element Type Description
HTMLInputElement number, range Returns the numeric value entered by the user.
HTMLOptionElement Any Returns the numeric value of the value attribute.