Friday, October 12, 2012

safety first with "global" javascript variables

This might be a "well duh!" for some of my audience, and I admit my need for this indicates some underengineering in my company's javascript component structure, but sometimes it's useful to pass information into one of our embedded components from the enclosing page via a global variable. ("Gasp!")

For a long time we were making this harder than it needed to be, because if you plan to have the page set something like

var global_hideFooter = true;

and then later do something in a component function like

if(global_hideFooter) { //do something 

it will break badly if called from another page that didn't set global_hideFooter one way or the other-- all the code in that block after the call to the non-existent variable will not be run.

However, if we realize that when you set a global in a browser (either by something like "var foo=" outside of any scope, or just start setting "foo =" anywhere) it gets implicitly included as a key/value on the "window" object. That means we can safely do

if(window.global_hideFooter) { //do something 

and it won't break if a page doesn't set it (and handily, in this case an unset value would act like false in a boolean context... defaults to false is a pretty natural coding paradigm.)

No comments:

Post a Comment