JavaScript Patterns

Page 30

Another antipattern that creates implied globals is to chain assignments as part of a var declaration. In the following snippet, a is local but b becomes global, which is probably not what you meant to do: // antipattern, do not use function foo() { var a = b = 0; }

// ...

If you’re wondering why that happens, it’s because of the right-to-left evaluation. First, the expression b = 0 is evaluated and in this case b is not declared. The return value of this expression is 0, and it’s assigned to the new local variable declared with var a. In other words, it’s as if you’ve typed: var a = (b = 0);

If you’ve already declared the variables, chaining assignments is fine and doesn’t create unexpected globals. Example: function foo() { var a, b; // ... a = b = 0; // both local }

Yet another reason to avoid globals is portability. If you want your code to run in different environments (hosts), it’s dangerous to use globals because you can accidentally overwrite a host object that doesn’t exist in your original environment (so you thought the name was safe to use) but which does in some of the others.

Side Effects When Forgetting var There’s one slight difference between implied globals and explicitly defined ones—the difference is in the ability to undefine these variables using the delete operator: • Globals created with var (those created in the program outside of any function) cannot be deleted. • Implied globals created without var (regardless if created inside functions) can be deleted. This shows that implied globals are technically not real variables, but they are properties of the global object. Properties can be deleted with the delete operator whereas variables cannot: // define three globals var global_var = 1; global_novar = 2; // antipattern (function () {

12 | Chapter 2: Essentials


Issuu converts static files into: digital portfolios, online yearbooks, online catalogs, digital photo albums and more. Sign up and create your flipbook.