I have this function (going trough the Eloquent Javascript Tutorial chapter 3):
function absolute(number) {
if (number < 0)
return -number;
else
return number;
}
show(absolute(prompt(“Pick a number”, “”)));
If I run it and enter -3 the output will be 3 as expectet but if I enter just 3 the output will be “3” (with double quotes). I can get around by changing
return number;
to
return Number(number);
but why is that necessary? What am I missing?
prompt()always returns a string, but when you enter a negative number, it is handed to the-numbercall and implicitly converted to aNumber. That doesn’t happen if you pass it a positive, and the value received byprompt()is returned directly.You can, as you discovered, cast it with
Number(), or you can useparseInt(number, 10), or you could do-(-number)to flip it negative, then positive again, or more obviously as pointed out in comments,+number. (Don’t do--number, which will cast it to a Number then decrement it)