Posts tagged ‘best practices’

Javascript is a fantastic language — in fact, it’s become the language that I do most of my programming in nowadays. It’s flexible, fast, and powerful. Unfortunately, though, it suffers from a few flaws, which, although not critical, can be frustrating. One of the potentially most confusing features is the with keyword, which promises a lot, but can really just make life difficult.

The with keyword might appear to be harmless enough: it allows you to avoid typing long references; instead of

ah.woom.ba.weh.lyric = 'In the jungle';

we can type

with (ah.woom.ba.weh) {
  lyric = 'In the jungle';
}

But what happens if we happen to have a global variable named lyric? In the example below, which lyric should be modified?

lyric = 'In the jungle';
with (ah.woom.ba.weh) {
  lyric = 'The mighty jungle';
}

The simplest way to deal with this issue is to use a variable:

var a = ah.woom.ba.weh;
a.lyric = 'The mighty jungle';

Now there is no ambiguity.

Based on a post by Douglas Crockford at the YUI Blog.