Skip to content

Instantly share code, notes, and snippets.

@soyuka
Last active August 29, 2015 14:07
Show Gist options
  • Save soyuka/03b7476b61866a892d7b to your computer and use it in GitHub Desktop.
Save soyuka/03b7476b61866a892d7b to your computer and use it in GitHub Desktop.
Opinion about global wrappers in nodejs
//global variable
test = 'hello';
//is exactly the same as
global.test = 'hello';
//local variable - this will definitly override your global variable
var test = 'hello';
//using the process scope, if, and really if, you can't do without a global variable
process.test = 'world';
//Now both will be defined and using `process` will avoid any confusion
console.log(test + process.test);
//hello world
@soyuka
Copy link
Author

soyuka commented Sep 30, 2014

@tylergaw
Copy link

Awesome, thanks for the examples. Definitely going to avoid the global.foo, like you show it can be overridden. Was really just using this to save a few possible keystrokes. Would rather do that than risk confusing someone else looking at the code.

@soyuka
Copy link
Author

soyuka commented Sep 30, 2014

Also, some modules are defining global variables and could be a headache when you define a variable and everything breaks.
For example, the famous colors package is extending String.

Global variables could become handy to store configuration objects so that you won't have to require it on each page.

The worst I've seen is the shelljs module.
If you use the global version you'll require this file.
Assuming you did:

global.config = {my: 'awesome', config: 'object'}
require('shelljs/global')
//no more configuration and hours of debugging

Why the heck?
The global.js file will export each key of the main file and L131 states:

//@
//@ ## Configuration
//@

exports.config = common.config;

... BOOM 😑

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment