0

Basically below code is doing comparision of rowind variable and displays alert, but somehow it gives output as Not Zero even if it is zero then also it gives output as "Not Zero", can any one let me know what can be it reason?

<head>
    <script language="javascript" type="text/javascript">

     var rowind = 0;
    var newind = ((rowind == '')) ? "Blank" : "Some number";

    //Output is Blank
    alert(newind);

    </script>
</head>
<body>
</body>
</html>
Sagar Shirke
  • 648
  • 9
  • 32

3 Answers3

1

You are checking whether the variable rowind is equal to empty string in your condition.

((rowind == '')) // this will return as false since you variable is not an empty string. Rather it contains a string with 0 character

if you want to compare the string, use the following.

((rowind == '0')) //This will return true since the string is as same as the variable.

Update

The question you are asking is related to javascript type casting.

The MDN Doc

Equality (==)

The equality operator converts the operands if they are not of the same > type, then applies strict comparison. If both operands are objects, then > JavaScript compares internal references which are equal when operands > refer to the same object in memory.

The above explains how the == operator works in javaascript.

In your example, the '' is converted to a number since it is being compared with a type number variable. so javascript treats '' as a number and '' is equal to 0. thus returns true in your condition.

console.log(0 == '0');  //True
console.log(0 == '');   //True
console.log('' == '0'); //False

The following is the strict comparison used as an example.

console.log(3 == '3') //True
console.log(3 === '3') //False
Community
  • 1
  • 1
Imesh Chandrasiri
  • 5,558
  • 15
  • 60
  • 103
1
0 == '' returns true in javascript

The left operand is of the type Number. The right operand is of the type String.

In this case, the right operand is coerced to the type Number:

0 == Number('')

which results in

0 == 0  // which definitely is true

And yes

0 === '' will return false

As , the identity operator === does not do type coercion, and thus does not convert the values when comparing.

Vibhesh Kaul
  • 2,593
  • 1
  • 21
  • 38
0

The comparison is between strings and '0' does not equal ''.

Because '0' != '' doesn't cast any of them to Boolean, because they are of the same type - String.

Ori Drori
  • 183,571
  • 29
  • 224
  • 209