Actually am trying the following one like..
<!DOCTYPE html>
<html>
<body>
<p>A number divided by a non-numeric string bees NaN (Not a Number):</p>
<p id="demo"></p>
<script>
var d = "10"; //typeof d is string
document.getElementById("demo").innerHTML = 100/d;
// or document.getElementById("demo").innerHTML = 100/"10";
</script>
</body>
</html>
OUTPUT its giving me like..
A number divided by a non-numeric string bees NaN (Not a Number):
10
Please explain me why its ing like this.
Thanks..
Actually am trying the following one like..
<!DOCTYPE html>
<html>
<body>
<p>A number divided by a non-numeric string bees NaN (Not a Number):</p>
<p id="demo"></p>
<script>
var d = "10"; //typeof d is string
document.getElementById("demo").innerHTML = 100/d;
// or document.getElementById("demo").innerHTML = 100/"10";
</script>
</body>
</html>
OUTPUT its giving me like..
A number divided by a non-numeric string bees NaN (Not a Number):
10
Please explain me why its ing like this.
Thanks..
Share Improve this question asked Oct 9, 2014 at 12:04 Ramesh_KondaRamesh_Konda 1113 silver badges12 bronze badges 6- "10" is not a non-numeric string, "AA" would be a non-numeric string. – Michael Commented Oct 9, 2014 at 12:06
- What do you want to see in output? – Serkan Commented Oct 9, 2014 at 12:08
- then output has to e NaN. But its giving 10. Thats my problem? @MiChael – Ramesh_Konda Commented Oct 9, 2014 at 12:10
- No, it should not e NaN. "10" IS a numeric string. – Utopik Commented Oct 9, 2014 at 12:11
- am expecting output as NaN. beacause typeof "10" is string @serkan – Ramesh_Konda Commented Oct 9, 2014 at 12:12
3 Answers
Reset to default 4Unary operators will attempt to convert the string to a number. It will only produce NaN if the string cannot by converted to a number.
You'll notice the same if you try the following, which will convert from hex to 10:
100/"0xA"
If one of the operands is a string, JavaScript will try to convert it to a number first (ie: "5" bees 5), or if unsuccessful, NaN is returned for the expression.
This is the reason why 100/"10" gives 10 and not NaN.
add +
to convert the variable to a number:
var d = "10"; //typeof d is string
document.getElementById("demo").innerHTML = 100 / +d;
// -----------------------------------------------^--
And for the opposite, you can do a typeof
check:
if (typeof d !== 'number') {
// ...
}