E.g. I write 5 and when I press the convert, it shows NaN. My JavaScript looks correct but for some reason, I get this error. I even tried the parseFloat
around the document.getElementById("input").value
but it didn’t fix the problem.
when you multiply by undefined
you get NaN
It is because I’ve used arrow function?
no, look at your multiplication, what are the values in there?
num * convert(num - 1)
but I don’t see something wrong. num is the document.getElementById("input").value
so why is undefined
?
num
is fine
what’s the value of convert(num - 1)
?
Well that’s the undefined
but why? I copy pasted the recursion from the exercice. It should work.
If you look at the code example on the hint page you are missing the return. Have the convert
function return a value and use that to set the textContent
.
Also .value
is a string, not a number and even though it will work I would suggest you implicitly convert it instead.
Summary
const convert = (num) => {
console.log(num);
if (num === 0) {
return 1;
} else {
return num * convert(num - 1);
}
};
document.getElementById("convert").onclick = () => {
document.getElementById("output").textContent = convert(
Number(document.getElementById("input").value)
);
};
This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.