Skip to content Skip to sidebar Skip to footer

In Javascript, Which Is Better `var Obj = Obj || {}` Or `if (obj === 'undefined' || Typeof Obj !== 'object')`

I want to know which of these methods is better: var Obj = Obj || {}; or if (Obj === undefined || typeof Obj !== 'object') { Obj = {}; } I've been told that the 2nd method is b

Solution 1:

The second method is simply more specific, so for the purpose of creating an object (if it does not already exist), it is better. The first method only tests if the object is "truthy", meaning if Obj was the number 5, it would still return the original Obj, whereas in the second method, Objmust be of type 'object' in order for its value to be preserved.

Practically speaking, there isn't much of a difference, because you rarely run into situations like above; the second method just tells the reader what you want, more specifically. I like the first method because it's shorter, but it depends on how specific you want to be.

Solution 2:

The only issue I see with the first method is that if someone has defined Obj to refer to something that isn't an object but also isn't falsey -- a non-zero integer, say -- then Obj will continue to point to that thing, and later calls to Obj that assume it is an object will fail. But I still prefer the first version for simplicity; I try to namespace such objects in such a way that no one will have assigned anything inappropriate to that name.

Post a Comment for "In Javascript, Which Is Better `var Obj = Obj || {}` Or `if (obj === 'undefined' || Typeof Obj !== 'object')`"