+prompt Vs Prompt In Javascript
Solution 1:
No.
The unary plus operator will convert the response in to a Number, not an integer.
It could give you a floating point value, it could give you NaN
.
If you want an integer then you need to check the response and then put in some error recovery for cases where the response is not what you want.
For example: If it is a floating point value, then you might want to just use Math.floor
to convert it. If it is NaN
then you might want to prompt
the user again.
Solution 2:
Well this is what happen's when you add plus before prompt, i.e. as below,
Eg :- 1
var a = prompt("Please enter a number");
console.log(a);
typeof(a);
Now in eg (1) when you enter a number and if you check that in console, it show a number but as that number is in-between double-quote, so in JavaScript it's a string, that's what it will show in typeof too when you console that.
Eg :- 2
var a = +prompt("Please enter a number");
console.log(a);
typeof(a);
Now when you console the var a and typeof
a of eg(2) the result differs as we have added + before prompt. So this time we get our prompt input value as number and not string. Try you will understand what I'm saying.
Solution 3:
The effect of +promt("...")
is that the result of the promt command will be cast to a number.
This is a nice hack, but not a clean solution.
I would recommend to assign the user input to a variable, then check it and in case it doesn't match the requirements, throw an exception or error message.
var
input = prompt("Please enter a positive number"),
inputNum = parseInt(input, 10);
if (isNaN(inputNum) || inputNum < 1)
alert("You did not enter a positive number.");
Solution 4:
So putting a +
before any data type converts it into a number.
I tried this:
typeof(+"100") ==> number
typeof(+"12.34") ==> number
typeof(+true) ==> number
typeof(+false) ==> number
Things got really weird when I experimented with the undefined
data type. e.g.:
x = +undefined
typeof(x) ==> Number whilst value of variable x is NaN
Solution 5:
+prompt()
is just a +
before a prompt()
, it's like writing +"3"
or +"10"
. It just tries to cast the outcome to a number.
Post a Comment for "+prompt Vs Prompt In Javascript"