Tag: syntax

  • Avoid Javascript’s ‘with’ keyword

    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
    [sourcecode language=’javascript’]ah.woom.ba.weh.lyric = ‘In the jungle’;[/sourcecode]
    we can type
    [sourcecode language=’javascript’]with (ah.woom.ba.weh) {
    lyric = ‘In the jungle’;
    }[/sourcecode]

    But what happens if we happen to have a variable in scope named lyric? In the example below, which lyric should be modified?
    [sourcecode language=’javascript’]var lyric = ‘In the jungle’;
    with (ah.woom.ba.weh) {
    lyric = ‘The mighty jungle’;
    }[/sourcecode]
    The simplest way to deal with this issue is to use a variable:
    [sourcecode language=’javascript’]var a = ah.woom.ba.weh;
    a.lyric = ‘The mighty jungle’;[/sourcecode]
    Now there is no ambiguity.

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