Alex Rivera | Logout

Why javascript treats 0 equal to empty string?

Asked 2012-09-14T09:49:05.627
33

Possible Duplicate:
Implied string comparison, 0='', but 1='1'

Executing the following case in javascript, I get 0 equal to '' (an empty string)

var a   =   0;
var b   =   '';//empty string
if(a==b){
    console.log('equal');//this is printed in console
}else{
    console.log('not equal');
}

Could anyone guide that what is the reason behind this?

Edit
Report

3 Answers

5

0, "" (Empty String), false all technically have the same value, when typecasted. If you need to strictly treat them, you can use ===.

It is the same with similar programming languages, like PHP.

var a = 0;
var b = ''; //empty string
if(a == b){
    console.log('equal'); //this is printed in console
}else{
    console.log('not equal');
}

To make a strict comparison:

if(a === b){
    console.log('equal');
}else{
    console.log('not equal'); //this is printed in console
}
answered 2012-09-14T09:51:32.187
2

== operator in javascript don't compare types so 0=='' === true (because as a number string '' evaluates to 0) or 0==false === true (because bool false evaluates to 0) to compare types to you can use === operator.

Here you'll find useful information about comparison.

answered 2012-09-14T09:50:28.927
1

Because empty string represented as number is zero. If you compare apples and oranges you should think of how your particular orange would look if it were an apple.

answered 2012-09-14T09:51:05.297

Your Answer