Are there any important differences (semantical, performance-related, etc.) between (1) and (2)?
var obj = obj || {};
var obj = Object(obj);
Context. The first is the way I've been sharing variables across Django's templates and my js files. I just came across a section in Rauschmayer 2014 ("Functions for Converting Boolean, Number, String, and Object", pg. 79), where he described Object(obj)
as follows:
obj
if obj
is an object,{}
if obj
is undefined
or null
,obj
is a primitive value.Given that (very informal) semantics (particularly the first two clauses), it seems to me that we can use (2) wherever we would use (1), but I'm not entirely sure what consequences this will have.
Rauschmayer, Axel (2014) Speaking JavaScript (free to read online).
Yes there is a difference, as the quote you gave already mentions. The first notation will return the primitive itself when obj
was a primitive. The second one will return a wrapped primitive, which is an object.
If the rest of the code relies on obj
being an object, the second notation is more defensive.
But then again, the first notation is more common, and one might wonder how a primitive value would be assigned to a variable named obj
anyway.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With