-1

I'm having trouble with a variable I set with a prompt. So I checked the variable in the console, and did not understand the result.

My questions is, how can a variable have a number for its value and undefined for its type?

Here is the code.

const inputNumber = prompt("Input a number");
console.log("inputNumber is " + inputNumber);
console.log("inputNumber's type is " + inputNumber.typeof);

and here is the output in the console if I put 5 in the prompt.

"inputNumber is 5"
"inputNumber's type is undefined"
Sean F
  • 11

1 Answers1

2

You need the typeof operator, not a property typeof, which is undefined for each string.

BTW, inputNumber is always a string, because of prompt.

For conversion to a number, you need to parse it (parseInt/parseFloat) or take an implicid conversion with unary plus +.

const inputNumber = prompt("Input a number");
console.log("inputNumber is " + inputNumber);
console.log("inputNumber's type is " + typeof inputNumber);
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392