Common pitfalls with JavaScript scope

I’m a firm believer that JavaScript’s flexibility is great for small projects with a single developer. But, its flexibility can become a seriously liability in medium to large projects if not managed properly. The ‘scope’ of a variable can cause some of the largest headaches for developers. And, in big projects tracking down an improperly scoped variable will take time, and it will try your patience.

In most cases, variables in JavaScript have two scopes: global and private. Scope is the context in which a variable is used. A global variable is defined outside of any function() in a JavaScript text block, and it can be accessed from inside any function(). Any change to a global variable will be reflected where ever else that variable is used. A private variable is defined only inside a function() and private variables are not accessible by other function()’s by definition. So a change to a private variable only changes it’s own value and doesn’t affect any other variable outside the scope of the function(). If you are new to scope, you may want to re-read this paragraph twice.

If you’ve been using JavaScript for any amount of time you’ll discover that simply misplacing a “var” statement in front of a variable causes it become global in scope. And, if you happen to already have a global variable somewhere else by the same name then these values can overwrite each other. If you are working on a project with thousands of lines of code and multiple .js libraries then your problems can get larger. I’ve accidentally deleted a “var” keyword in several cases and then spent a considerable head banging tracking it down.

To demonstrate these pitfalls, I’d rather show you in code what the problems are. Hopefully by reading this, and understanding a bit more about scope and by using best practices, you’ll avoid the common pitfalls as much as possible.

Scenario 1– properly defined private variables. This scenario demonstrates best practices for defining local variables within a function(). You can have privately scoped variables with the same name as global variables because of JavaScript obeying adherence to scope. Click here to try out this scenario.

  //This sets a global variable scope
  var color = "blue";

  function init() {

	var me = new Person("Andy");
	alert(" Private scoped name: " + me.name +
	   "\r\n Private scoped color: " + me.favoriteColor +
	   ", \r\n Global scoped color: " + color
	);

  }

  function Person(myname)
  {
	  //This creates a privately scoped variable
	  //Does not affect or change the globally scoped
	  //variable of same name
	  var color = "red";

	  //myname exists within the private scope of the function
	  //color is privately scoped
	  this.name = myname;
	  this.favoriteColor = color;
  }

Scenario 2 – improper use of a global variable. This scenario demonstrates forgetting to set “var” on the variable color. The value of the global variable named color is changed. If you use this pattern for manipulating global variables you are asking for trouble as your project grows larger. Click here to try out this scenario.

  //This sets a global variable scope
  var color = "blue";

  function init() {

	var me = new Person("Andy");
	alert(" Private scoped name: " + me.name +
	   "\r\n Private scoped color: " + me.favoriteColor +
	   ", \r\n Global scoped color: " + color
	);

  }

  function Person(myname)
  {
	  //This changes the globally scoped
	  //variable of same name
	  color = "red";

	  //myname exists within the private scope of the function
	  //color exists within the global scope of the application
	  this.name = myname;
	  this.favoriteColor = color;
  }

Scenario 3 – this scenario shows the best practice for passing in a global variable to a function(). By passing the global variable into someColor you protect the scope of it within the function(). Click here to try this scenario.

  //This sets a global variable scope
  var color = "blue";

  function init() {

	var me = new Person("Andy", color);
	alert(" Private scoped name: " + me.name +
	   "\r\n Private scoped color: " + me.favoriteColor +
	   ", \r\n Global scoped color: " + color
	);

  }

  function Person(myname, someColor)
  {
	  //myname exists within the private scope of the function
	  //someColor is a private scope, but it inherits the value
	  //of the variable passed to it.
	  this.name = myname;
	  this.favoriteColor = someColor;
  }

References:

Scope in JavaScript by Mike West
Variable Scope for New Programmers by Jonathan Snook

10 Tips and Tricks for Running Live Demos on a Mobile Phone

Here’s my short list of some things to consider when you demo your company’s mobile apps to a live audience. I’ve accumulated this list over the last several years as the team I’m on does a lot of showing off apps on iOS, Android and Windows Phone. We’ve also seen quite a few demos from customers and at industry conferences.

While most of these tips apply to personal demos where you have the phone in your hand while standing in a tradeshow booth, I’m actually talking about projecting demos on a big screen in front of a live audience, or during an internet video conference call with screen sharing.

  1. Screen brightness. Adjust the screen brightness so that the screen is not too dark and not washed out, and temporarily disable screen brightness auto-dimming. Auto-dimming is where the phones background light gets dimmed usually around ten to fifteen seconds before the screen auto-locks.
  2. Turn off auto-lock. Temporarily disable your auto-screen lock (if your company policy permits it). There’s nothing more aggravating than talking about something for a few minutes and then when you turn your attention back to the phone you have to re-enter your unlock code. I’ve also seen this happen to people on the screen behind them and they didn’t notice but the audience could see it.
  3. Silence the phone. For demos that don’t need sound, which is probably most demos, turn your phone’s sound all the way to “off”. Most phones beep, tweedle and pop as various things happen in the background, so spare your audience by making your phone silent.
  4. A/C Power. Plug your phone into a power outlet. While this may seem obvious, I’ve seen a phone die during a major industry conference plenary session.
  5. Shutdown extra apps. Shut off any unnecessary apps that will consume memory and CPU. You want your demo to run as fast as possible.
  6. Remove unnecessary icons. Clean any non-professional app icons from the navigation screens you will be showing live. On a few rare occasions I’ve seen some fairly disturbing icons that had no place in a professional presentation.
  7. Verify the type of demo camera. Ask ahead what kind of demo camera the conference has for mobile phones, one of the most common ones is called an ELMO. These are devices where you set your phone below it and it has a camera that points downward at the phone and connects to a projector through a switch. So, when you go to show off your app you turn a switch that connects the ELMO (or similar device) to the projector. Some of these are terrible and some are great. I use an IPEVO Point 2 for some demos because it’s portable and I trust it.
  8. Test demo camera. Test your demo camera well before your presentation. You may need some help from the conference’s audio visual team. Make sure your phone in focus, check if you can see the application details, look to see if the background colors aren’t too white and washed out, etc.
  9. Cache local data. Cache your data when possible. If you plan on connecting to remote data sources, consider moving that data onto a local SQLite database on your phone.
  10. Check internet connection. Check your internet connection beforehand. Conference are notorious for having limited cell and wireless coverage. My recommendation is always create a movie backup of your most important demo points. Yep, I’m 100% serious. With an IPEVO Point 2, for example, you can project the camera image in a desktop app and use software such as Camtasia Studio, which also offers a free trial, to create a movie with audio too. Also, a note to phone developers here, it’s a best practice to check if your app has an internet connection and to let your users know if the connection goes away, for example: https://www.andygup.net/?p=155.

The Largest Conference For Mapping and Geospatial Developers – Esri DevSummit 2012

I’ll be presenting at the Esri DevSummit next week so if you are attending please swing by my sessions and say “hi”. If you aren’t familiar with Esri or the conference, about 1400 developers and other technical experts converge on Palm Springs, California every Spring to learn all things technical about building commercial and enterprise geographic information systems. There will be everything from introductory Dojo workshops to deep dives into the heart of our APIs.

If you’re around here’s my schedule. I’d be very interested to hear about what you are working on:

Monday,  March 26

Getting Started with the ArcGIS Web APIs – 8:30am – 11:45am, Pasadena Room. I’ll be presenting the portion related to our ArcGIS API for JavaScript.

Gettings Started with Smartphone and Tablet ArcGIS Runtime SDKs – 1:15pm – 4:45pm, Pasadena Room. In this session, I’ll be presenting on our ArcGIS Runtime SDK for Android.

Wednesday, March 28

Flex the World – 10:30am, Demo Theater 2. I’ll be presenting with my esteemed colleague Sajit Thomas on Apache Flex.