4 ms·
Good tips. Specially comparison operators. The fact Javascript has both "null" and "undefined" is not just a stupid idea, but might be the biggest source of st
by hcarvalhoalves 14y ago
Good tips. Specially comparison operators.
The fact Javascript has both "null" and "undefined" is not just a stupid idea, but might be the biggest source of stupid bugs. You need a long, repetitive construct everytime you check a variable:
if((typeof banana === "undefined") || (!banana)) {
banana = "banana";
}
But instead you see code like:
if(banana == null) {
...
}
Argh!
- thezilch 14y agoif(!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 ;)