Javascript Prompt

0

Does the prompt return by default String correct? The function Number does the return conversion of the prompt that is String to number. So when I run the following function and I put numbers in quotes does the message NaN appear, should not I convert the return to number and execute the calculation?

var num = Number(prompt("Digite um número", ""));
alert("Seu número é a raíz quadrada de " + num * num);
    
asked by anonymous 12.07.2018 / 23:35

1 answer

1

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

An input of 12 in prompt will be as if you typed:

let texto = "12";

But an input of "12" is as if it had written:

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

Note that it has quotation marks inside% s of% itself as one of its characters. So when string tries to convert it gets a parseInt and fails because it is not numeric, resulting in " - Not a Number .

Test:

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

console.log(parseInt(texto));
console.log(parseInt(texto2));
    
12.07.2018 / 23:55