Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

(obj || {}) vs Object(obj)

Tags:

javascript

Are there any important differences (semantical, performance-related, etc.) between (1) and (2)?

  1. var obj = obj || {};
  2. 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,
  • [wrapped primitive] if 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).

like image 235
Readingtao Avatar asked Jul 11 '15 19:07

Readingtao


1 Answers

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.

like image 195
GolezTrol Avatar answered Sep 29 '22 02:09

GolezTrol