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 better, but I don’t know why. Please can you explain to me what are pros and cons of each.
Many thanks
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
Objwas the number 5, it would still return the originalObj, 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.