Skip to content Skip to sidebar Skip to footer

Triple Equals Gives Wrong Output When Strings Are Compared, But In Case Of Integer It Gives Correct Output

I have an array of string like var a = ['a','a','a']; When I do comparison like a[0]==a[1]==a[2] it gives me result as false but when I change the value of array to ['1','1','1']

Solution 1:

What you need is

a[0]==a[1] && a[0]==a[2]

In your case, when you are comparing ['1','1','1'], what happening is

a[0] == a[1]  // truetrue == a[2]  // true as true == '1'

Solution 2:

What happens is that it executes it like this:

 ((a[0]==a[1])==a[2]):

1.

(a[0] == a[1]) => true

2.

(true == a[2]) => false

Because: 1 == true, the array [1,1,1] returns true

Solution 3:

It's easier to understand if you test the inner value direct: 0==0==0 is understood as (0==0)==0, so 0==0 is true, what's tested next is (true)==0, 0 is interpreted as false, and true==false is false.

For the other comparisons the first part is the same, but 1 or 9 are interpreted as true.

Solution 4:

This is expected output

// Case 1
var a = ['a','a','a'];

The output of 

a[0] == a[1] -->true

Next Comparison

true == a[2] -->false// true != 'a';// Case 2

var a = ['1','1','1'] ;

a[0] == a[1] -->truetrue == a[2] -->true// true == "1"

However, in case 2 if you use strict equality operator then the result will be false.

var a = ['1','1','1'] ;

// strict equality operatorconsole.log(a[0]===a[1]===a[2]);

// without strict equality operatorconsole.log(a[0]==a[1]==a[2]);

Solution 5:

If you see the associativity of operator == it is left-to-right. So in your case

when var a = ['a','a','a']; a[0]==a[1]==a[2] this evaluate a[0]==a[1] first then result of this with a[3] means true == 'a' which returns false.

In case when var a = ['1','1','1']; so as per associativity this evaluates from left to right in expression a[0]==a[1]==a[2] results '1' == '1' in first, then true == '1' in second which gives true finally.

In case when var a = ['9','9','9']; first '9' == '9' then true == '9' which finally evaluates to false. Hope this helps.

Post a Comment for "Triple Equals Gives Wrong Output When Strings Are Compared, But In Case Of Integer It Gives Correct Output"