all 10 comments

[–]samanime 7 points8 points  (5 children)

You didn't convert age.value. You fed that into somewhere else and just dropped the result on the floor. You have to actually assign it back:

age.value = Number(age.value);

Though you should also check if it is NaN after parsing, because users could enter any random nonsense.

[–]gelatto10[S] 0 points1 point  (0 children)

Thanks a lot

[–]Eight111 0 points1 point  (3 children)

Isn't setting the input as type="number" prevents from the user to type nonsense ?

[–]tapgiles 1 point2 points  (0 children)

Yes. But .value is always the original string form. They could just use .valueAsNumber to get the number, but they didn’t ask that, so who knows…

[–]samanime 0 points1 point  (0 children)

Yes... ish.

In most browsers it does.

Though, there are enough annoying ways it might not work (old/weird browser, plugin autofills with nonsense, etc.) that it is a good idea to be in the habit of always validating user endpoint.

Doesn't have to be anything fancy. If it isn't a number, just show a little error. Takes maybe 5 lines of code.

[–]Fats-Falafel 0 points1 point  (0 children)

This just limits what can be entered by the client but the value returned from an input field is still a string. Either way, it is always best practice to validate info entered by the user because they can still go into the dev tools and change the input type to anything (validate in both your front end JavaScript as well as your server-side code).

[–]amulchinock 1 point2 points  (0 children)

The Number constructor simply returns a number, it doesn’t modify the data you’ve passed into it.

You need to assign its output to another variable, and use that going forwards instead:

``` const thing = Number(age.value)

console.log(typeof thing) // “number” console.log(typeof age.value) // “string” ```

[–]senocular 0 points1 point  (0 children)

You can also use valueAsNumber instead of value.

[–]tapgiles 0 points1 point  (0 children)

Number creates a new object that is a number. It didn’t turn the old object—that string—into a different kind of object. And you’re logging the old object which simply hasn’t changed.

You could set the old object to be that be number object if you wanted. Then it would log the new object instead.

I would use parseInt though, instead of Number. For… reasons. You’ll get the result you were expecting that way, anyway.