+ 5

Could anyone explain me why the result of this question is b? Aren't a and b identical (same type and same value)?

var a = new String ("Hello"); var b = new String ("Hello"); if (a === b) { alert ("a"); } else { alert ("b"); }

30th Mar 2019, 11:51 AM
Leonardo
Leonardo - avatar
11 Respuestas
+ 9
HonFu exactly! a= "hello" b= "hello" Here there's just one "hello" in the string pool and both a and b are referencing to that one instead of having two distinct "hello" for a and b which is the case when you create string using string constructor.
30th Mar 2019, 12:51 PM
Шащи Ранжан
Шащи Ранжан - avatar
+ 7
You're creating two distinct instances of String class. Although both contains same value but still the two are different instances and hence a==b is false.
30th Mar 2019, 12:34 PM
Шащи Ранжан
Шащи Ранжан - avatar
+ 4
HonFu lol yeah and that's why it's the easiest language.. No such confusion 😅
30th Mar 2019, 12:57 PM
Шащи Ранжан
Шащи Ранжан - avatar
+ 3
M. Watney, but usually you can compare two equal strings, getting true, right? How does this work? Is JS storing only one string of the same value like Python unless you specifically say otherwise by instantiation?
30th Mar 2019, 12:47 PM
HonFu
HonFu - avatar
+ 2
At least as long as you stick to the builtins with their clear immutable-mutable behavior. write a class Str that holds a str for you and things may go differently. ;)
30th Mar 2019, 1:00 PM
HonFu
HonFu - avatar
+ 2
Thanks to all!! I'm a newbie in programming but now it's clear!!
30th Mar 2019, 1:28 PM
Leonardo
Leonardo - avatar
+ 1
Hm, funny, Python pools them even if you instantiate. Good to know, thanks!
30th Mar 2019, 12:54 PM
HonFu
HonFu - avatar
+ 1
Does Java have a special "===" meaning? I'm not familiar with Java enough to decide if that might be the bug or if it is a legit thing.
31st Mar 2019, 2:49 AM
Michael Williams
Michael Williams - avatar
31st Mar 2019, 4:00 AM
CHANDAN JENA
+ 1
If we tweak the code a little - var a = new String ("Hello"); var b = a; if (a === b) { alert("a"); } else { alert("b"); } //Now the answer will be - a //This is because now both the variables //are referencing the same object unlike //the original code
31st Mar 2019, 8:04 AM
Kushagra Agarwal
Kushagra Agarwal - avatar