4 ms·
if(!window.banana) banana = "banana";
by thezilch 14y ago
if(!window.banana) banana = "banana";
- masklinn 14y agoI generally prefer: var banana; if (!banana) babana = "banana"; or var banana; banana = banana || "banana"; I have a strong dislike for implicit globals — even at the toplevel — and the global object isn't necessarily `window` (it's not in the Spidermonkey or Node shells for instance, I'm not sure it is in Web Workers — there's a WorkerGlobalScope object but i don't know if it's bound to a global called `window`). If `undefined` has to be checked for explicitly (because `null` or `0` or `""` are valid values), check `banana === undefined` (or `banana === void 0` if your coworkers are assholes)
- thezilch 14y agoI don't disagree; it was just the briefest example, which assumed that window was the scope -- couldn't really think of a reason I'd warrant an inner scope to have uninitialized vars. So, to the OP, you can always check that your var is a member of some object, including window. The typeof example is bad form.
- hcarvalhoalves 14y ago"If there's no attribute on the window object, let's define a global" In any other language this would mean a complete different thing. This can only be obvious in the world of Jamie Zawinski.
- draven 14y agoWhy Zawinski? Do you mean Brendan Eich?
- hcarvalhoalves 14y agoHa! You're correct. It's because I attribute Netscape as being the culprit for Javascript being around ;)