Hey guys please help me to find out this problem solution.The ans is b. How it come? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 2

Hey guys please help me to find out this problem solution.The ans is b. How it come?

<script> var a = new String("hello"); var b = new String ("hello"); if (a===b){ alert("a"); }else{ alert ("b"); } </script>

8th Apr 2019, 5:21 PM
KHUSHbu
KHUSHbu - avatar
3 Answers
+ 5
When u create instance of string, their type diifers. Hence, === operator returns a false. Hence, b is alerted.
8th Apr 2019, 6:45 PM
Arushi Singhania
Arushi Singhania - avatar
+ 5
Its not a difference of type but a difference of instance. Both A and B are the same object type but they’re different instances, the ”===” operator compares if both are the same. To better inlustrate this, if you were to simply have: var a = ”hello”; var b = ”hello”. Your if statement would evaluate to true, this is because both are of type String and they contain the same values. Using the new keyword you’re creating strings as Objects and Objects store an instance reference which will make them differ. Hope it helped and I didnt overcomplicate things.
8th Apr 2019, 7:22 PM
Victor Andersson
Victor Andersson - avatar
+ 2
You create two diffrent objects with the new keyword. So it cant be equal, because they arent the same object. Although the values of those are the same. So the comparison throws false.
8th Apr 2019, 6:48 PM
avatarluca
avatarluca - avatar