0

Why it alert's string when you enter a number.?

https://code.sololearn.com/WTPojwGulhn4/?ref=app

18th Apr 2018, 8:45 AM
Sina
Sina - avatar
8 Answers
+ 2
It's the default return type from a prompt. I'd suggest to use the isNaN statement to test (is Not a Number), which understands if the value of the variable is not usable as a number. Just add the not logical operator (!) and you've done. function a() { var b = prompt("Enter s.th"); var type; if (!isNaN(b)) type = 'It is a Number!'; else type = 'It is a String!'; alert(type); } a()
18th Apr 2018, 8:59 AM
Luigi
Luigi - avatar
+ 2
because the default value of a type of data received in a prompt is string
18th Apr 2018, 9:08 AM
Moniue Raj
+ 1
Obviously we can reverse the code to be more straightforward: if (isNaN(b)) type = 'It is a String!'; else type = 'It is a Number!';
18th Apr 2018, 12:32 PM
Luigi
Luigi - avatar
+ 1
Yes I underestood thanks
18th Apr 2018, 12:36 PM
Sina
Sina - avatar
0
Ok thanks
18th Apr 2018, 12:05 PM
Sina
Sina - avatar
0
I have a question you wrote if(!isNaN(b)){ type="it's a number" } it means if b is not a number
18th Apr 2018, 12:14 PM
Sina
Sina - avatar
0
Please note the ! before the isNaN statement, that means it will reverse the value of isNaN(b). // User wrote 7 isNaN(b) = false !isNaN(b) = true //User wrote “hello” isNaN(b) = true !isNaN(b) = false
18th Apr 2018, 12:22 PM
Luigi
Luigi - avatar
0
Ok
18th Apr 2018, 12:28 PM
Sina
Sina - avatar