Strange Behavior of Javascript

Hello everyone,

I found some strange behavior of Javascript. Let’s look below Javascript statements:

 var myArra = [null,undefined,[]];  
console.log(myArra == ',,');

When I’m going to execute above statements in my firebug console, console.log returns ‘true’. I don’t know why and how can it possible because I’m comparing array with the string value. Can anyone explain why Javascript behaves this?

Let’s look one more scenario

 var myArra = [0];  
console.log(myArra == ! myArra);

Above statement also logs ‘true’ in my firebug console. Anyone have any idea on this?? Can anyone explain above both scenario??


6 thoughts on “Strange Behavior of Javascript

  1. First is correct as == compares value not strict with type.For second one, === is a strong compare by it's type matching also.Try this console.log(myArra !== myArra); it will give you false

  2. Thanks Vikas for your comment. And I agreed with the first one but what with second one? '!' means not and if you try console.log(true == !true) then it will give 'false' But why console.log(myArra == !myArra) gives 'true'.

  3. Nirav,As Vikas said == operator tried for type conversion. When you are writing myArr == !myArr where myArr tried to convert into Boolean due to ! Get highest priority. Since myArr is not Boolean. And it may go in following way … Array to string to number to Boolean and result is true so !true is false. MyArr == false so myArr will now convert to Boolean in same manner and this will be true and the result is true == false which is obviously FALSE.

  4. Thanks Priteshbhai so as you say Array to string to number to boolean conversion so ! myArray will '0' to 0 number and then false but !false = true??? Also at end you said true==false which is false but console.log(myArra == ! myArra); gives 'true'. Is there anything wrong with my understanding???

  5. If myArr is empty then it will be 'false' but since it has three elements so it should return true. may be you want to try again myArra == !myArra since I am getting result as false.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s