Monday, July 15, 2013

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 comments:

  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

    ReplyDelete
    Replies
    1. 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'.

      Delete
  2. 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.

    ReplyDelete
    Replies
    1. 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???

      Delete
  3. 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.

    ReplyDelete
    Replies
    1. If myArr = [0]; then console.log(myArr == !myArr); gives 'true'. But if myArr = [1]; then console.log(myArr == !myArr); gives 'false'.

      Delete