Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

+prompt vs prompt in JavaScript

Tags:

javascript

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 ?

like image 358
Newcomer Avatar asked Jun 24 '16 10:06

Newcomer


People also ask

What is the difference between prompt and +prompt?

+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.

What is the difference between window prompt and prompt in Javascript?

Nope, they're the same.

What does prompt mean in Javascript?

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)

How does prompt differ from alert?

alert. shows a message. prompt. shows a message asking the user to input text.


2 Answers

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.

like image 94
Quentin Avatar answered Nov 07 '22 21:11

Quentin


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.

like image 44
frnt Avatar answered Nov 07 '22 19:11

frnt