Why doesn’t the function areaRettangolo
return a number?
I want to calculate the area of a rectangle using a function called areaRettangolo
but it returns Nan
let base = document.getElementById('base');
let altezza = document.getElementById('altezza');
let bottone = document.querySelector('button');
let testo = document.querySelector('h1');
let area = 0;
function areaRettangolo(a, b) {
let c = 0;
c = a * b;
return c;
}
bottone.addEventListener('click', () => {
area = areaRettangolo(base, altezza);
console.log(area);
});
<input type="number" id="base" placeholder="inserisci la base del rettangolo"><br><br>
<input type="number" id="altezza" placeholder="inserisci l'altezza del rettangolo"><br><br>
<button>Calcola l'area del rettangolo</button>
<h1>-</h1>
3
Answers
It returns
NaN
(Not a Number) because when you executec = a * b;
JavaScript expectsa
andb
to be numbers or types that can be converted to a number (for example, a numeric string"123"
can be converted to the number123
).In your code
a
andb
are both aHTMLElement
which cannot be converted to aNumber
automatically.Use
.value
in conjunction withparseInt
orparseFloat
to get the current value of the element (useparseInt
if you expect/allow only whole numbers,parseFloat
otherwise):You don’t need to change anything inside the
areaRettangolo
function.This is happening because
base
andaltezza
are HTMLElements and not the numbers you are expecting. To get the inserted numbers you need to sendinput.value
to the function instead.The inputs
base
andaltezza
are of typenumber
soinput.valueAsNumber
is a better alternative, as it returns the values as numbers instead of strings.Be carrefull,
input.valueAsNumber
works only for some input types as shown in this question.You must use .value after altezza and base.
Becouse document.getElementById return a HTMLElement tag and you do’nt have
direct access to values them! (value)
Htmls Code :