+ 1

Array equalization returning false

var arr1 = [10,20,30,"asd"]; var arr2 = [10,20,30,"asd"]; console.log(arr1==arr2); console.log(arr1===arr2); Both are returning false. Why ?

30th Oct 2019, 5:13 AM
Ajit Kumar
Ajit Kumar - avatar
6 Answers
+ 5
Because arr1 and arr2 are two different objects. Although their values are the same. For example suppose that me and you both have equal money but still we are different persons. "==" in JavaScript compairs objects by themselves not their valves. If you want to get true as result you must first write: arr1 = arr2
30th Oct 2019, 6:47 AM
Qasem
+ 3
Noise Of Silence I repeat my las answer with example: str1 = "String" str2 = "String" str1 == str2 => true (because they aren't "objects") str1 = new String ("String") str2 = new String ("String") str1 == str2 => false (because they are "objects" now)
30th Oct 2019, 7:42 AM
Qasem
+ 2
Qasem is very correct. And I particularly like the human-money illustration. In addition I will say try studying 'Pass by reference.' Nice question by the way đŸ‘đŸœ
30th Oct 2019, 7:04 AM
NuminousC
NuminousC - avatar
+ 2
Qasem NuminousC (o() is console.log function) var bool1 = true; var bool2 = true; o(bool1 == bool2); o(bool1 === bool2); var str1 = "String"; var str2 = "String"; o(str1 == str2); o(str1 === str2); Still false ?
30th Oct 2019, 7:14 AM
Ajit Kumar
Ajit Kumar - avatar
+ 1
Noise Of Silence pay attention to "object" term. If you define str1 and str2 as string objects (with new keyword) then they won't be equal.
30th Oct 2019, 7:26 AM
Qasem
0
Qasem all four outputs are true. Both for Boolean and string
30th Oct 2019, 7:29 AM
Ajit Kumar
Ajit Kumar - avatar