I have the following:
var a = 0;
if (Number(a) != '')
{
alert('hi');
}
I never get the alert even though a is not empty, it is 0 and I need this value for numeric calculations.enter code here
What's going on here?
I have the following:
var a = 0;
if (Number(a) != '')
{
alert('hi');
}
I never get the alert even though a is not empty, it is 0 and I need this value for numeric calculations.enter code here
What's going on here?
try the following
var a = 0;
if (Number(a) !== '') {
alert('hi');
}
If you compare two values using ==
or !=
operator, javascript type-coerces both of them and then compares. On the contrary, if you use ===
instead of ==
(or !==
instead of !=
), type coercion does not happen.
The !=
operator does type conversion if needed, so ''
is converted to the numeric value 0
.
You can use the !==
operator to avoid the type conversion:
var a = 0;
if (Number(a) !== '')
{
alert('hi');
}
You are comparing 0 != 0 which will always be false.
The main issue is that the implicit cast here is causing ''
to become 0
. This can be easily verified.
alert(Number(''));//0
But why does this happen? It is defined behavior in the Language Specification as seen at
9.3.1 ToNumber Applied to the String Type
http://www.ecma-international.org/ecma-262/5.1/#sec-9.3.1
The conversion of a String to a Number value is similar overall to the determination of the Number value for a numeric literal (see 7.8.3), but some of the details are different, so the process for converting a String numeric literal to a value of Number type is given here in full. This value is determined in two steps: first, a mathematical value (MV) is derived from the String numeric literal; second, this mathematical value is rounded as described below.
The MV of StringNumericLiteral ::: [empty] is 0.
This is why the value of implicitly converting an empty string to a number is 0.
Going forward, it would make more sense to check for a number by using isNaN
to ensure that a number was entered by the user or is present in the variable.
var a = 0;
if (!isNaN(a))
{
alert('a is a number');
}