In javascript, which is better than `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 was told that the second method is better, but I do not know why. Please, can you explain to me what are the pros and cons of each.

Thank you very much

+4
source share
2 answers

The second method is simply more specific, so for the purpose of creating an object (if it does not already exist), this is better. The first method only checks whether the object is "true", that is, if Obj was 5, it will still return the original Obj , whereas in the second method, Obj must be of type "object" in order to preserve its value.

In fact, there isn’t much difference because you rarely encounter situations like the one above; the second method simply tells the reader what you want, more precisely. I like the first method because it is shorter, but it depends on how specific you want to be.

+2
source

The only problem that I see in the first method is that if someone defined Obj to refer to something that is not an object but also not false - a non-zero integer, say - then Obj will continue to point on this thing, and then calls Obj , which suggest that the object will fail. But I still prefer the first version for simplicity; I am trying to skip such objects so that no one assigns anything so inappropriate for this name.

+2
source

Source: https://habr.com/ru/post/1379192/


All Articles