Is it good to use +prompt
instead of just regular prompt
in JavaScript if I want only integer numbers to be typed in my prompt window? Does it say something like that about +prompt
in the JavaScript standard/rules ?
+prompt() is just a + before a prompt() , it's like writing +"3" or +"10" . It just tries to cast the outcome to a number. It will change the string the prompt returns into a number.
Nope, they're the same.
The prompt() method is used to display a dialog box with an optional message prompting the user to input some text. It is often used if the user wants to input a value before entering a page. It returns a string containing the text entered by the user, or null. Syntax: prompt(message, default)
alert. shows a message. prompt. shows a message asking the user to input text.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With