Guest User

Untitled

a guest
Mar 23rd, 2018
85
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.08 KB | None | 0 0
  1. Note: Many developers believe there should never be any variables in the global namespace, and that everything should be contained in modules and private/separate namespaces. This is great in theory but nearly impossible in practicality; still it's a good goal to strive toward! Fortunately, ES6 added first-class support for modules, which will eventually make that much more practical.
  2.  
  3. As a simple example, imagine having a "debug mode" in your program that is controlled by a global variable (flag) called DEBUG. You'd want to check if that variable was declared before performing a debug task like logging a message to the console. A top-level global var DEBUG = true declaration would only be included in a "debug.js" file, which you only load into the browser when you're in development/testing, but not in production.
  4.  
  5. However, you have to take care in how you check for the global DEBUG variable in the rest of your application code, so that you don't throw a ReferenceError. The safety guard on typeof is our friend in this case.
  6. ```js
  7. // oops, this would throw an error!
  8. if (DEBUG) {
  9. console.log( "Debugging is starting" );
  10. }
  11.  
  12. // this is a safe existence check
  13. if (typeof DEBUG !== "undefined") {
  14. console.log( "Debugging is starting" );
  15. }
  16. ```
  17. This sort of check is useful even if you're not dealing with user-defined variables (like DEBUG). If you are doing a feature check for a built-in API, you may also find it helpful to check without throwing an error:
  18. ```js
  19. if (typeof atob === "undefined") {
  20. atob = function() { /*..*/ };
  21. }
  22. ```
  23. Note: If you're defining a "polyfill" for a feature if it doesn't already exist, you probably want to avoid using var to make the atob declaration. If you declare var atob inside the if statement, this declaration is hoisted (see the Scope & Closures title of this series) to the top of the scope, even if the if condition doesn't pass (because the global atob already exists!). In some browsers and for some special types of global built-in variables (often called "host objects"), this duplicate declaration may throw an error. Omitting the var prevents this hoisted declaration.
Add Comment
Please, Sign In to add comment