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.

2009-07-21 – 6:38 pm

Are you using jQuery? I found it to be very fast and much easier syntax than JavaScript.

2009-07-21 – 7:19 pm

I actually use MooTools by preference — it provides many of the same benefits as jQuery, and the syntax is similar.

Martin
2009-08-26 – 5:41 pm

Think you might not have grasped the main benefit of with … it’s for setting lots of properties, e.g.

var oMyElement = document.createElement( 'DIV' );
with ( oMyElement )
{
id = 'Fred';
with ( style )
{
width = '100px';
height = '100px';
display = 'inline';
}
}

2009-08-26 – 6:38 pm

Yes, you’re right that with can be very useful — but to my mind, the danger of not knowing exactly what you’re changing outweighs the potential benefit. Personally, I would use the MooTools method of setting lots of properties…

var oMyElement = new Element('div', {
id: 'Fred',
styles: {
width: '100px',
height: '100px',
display: 'inline'
}
});

…which means that I can get away without using with. :)

Add your voice

Spam protection by WP Captcha-Free