Prompt Javascript

Asked

Viewed 414 times

0

The return of prompt is by default String correct? The function Number does the prompt return conversion which is String to number. Pq then when I run the following function and place numbers between quotation marks NaN, should not convert the return to number and run the calculation?

var num = Number(prompt("Digite um número", ""));
alert("Seu número é a raíz quadrada de " + num * num);

  • Here ta working. Input: 10; Output: Your number is the square root of 100

  • Tries to put the value in quotes, a String.

  • Leandrade, it’s like you said, the return of a prompt is a string by default. Putting 12 or "12" will be string anyway. The difference is that you can convert 12 directly, and "12" does not.

1 answer

1


The problem is that you are not visualizing the string which will be interpreted by parseInt.

A input of 12 in the prompt it’ll be like I wrote:

let texto = "12";

But a input of "12" it’s like I wrote:

let texto = "\"12\""; //ou texto = '"12"';

Notice there are quotes inside string as one of her characters. So when the parseInt tries to convert a catch " and fails because it is not numerical, resulting in NaN - Not a Number.

Testing:

let texto = "12";
let texto2 = "\"12\"";

console.log(parseInt(texto));
console.log(parseInt(texto2));

  • Cool Isac, really did not know how was interpreted the number with quotes.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.