2

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?

Stanza
  • 485
  • 1
  • 4
  • 17
  • 1
    That's because of implicit type-coercion due to `!=`, use `!==`. And both empty string and number 0 are **falsy** values. – Tushar Jan 21 '16 at 09:24

4 Answers4

2

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.

Community
  • 1
  • 1
segmentationfaulter
  • 1,045
  • 2
  • 12
  • 13
2

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');
}
Guffa
  • 687,336
  • 108
  • 737
  • 1,005
  • Excellent that worked, !== flew right over my head as I have been doing way too much C# progamming ! – Stanza Jan 21 '16 at 09:56
0

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');
}
Travis J
  • 81,153
  • 41
  • 202
  • 273
0

use the !== operator to avoid type conversion

John
  • 107
  • 9