LA.NET [EN]

Sep 21

When I first noticed the with statement, I thought I had discover the “holly grail” of code simplification in JS. Take a look at the following snippet:

var student = {
    name: "luis",
    address: "fx",
    hobbies: ["computers", "soccer", "tv"]
};
with (student) {
    name = "john";
    address = "lx";
}

Well, everything looks good, right? And yes, in such a simple scenario, that is true. Now, the thing is that with will “augment” the current “context” with the object that you pass to it. In practice, and looking at the previous example,this means that you can use the name property of the student instance without using the instance variable name.

Before you go away,take an extra 30 seconds and look at the next snippet:

var name = "some other";
with (student) {
    name = "john";
}

If you run the previous snippet, you’ll see that within the with block, name refers to student.name and not to the global name variable. In practice, whenever you access an identifier from within a with block, the interpreter starts by checking if the object has a property with that name (that is, if obj.propName is not undefined). When that happens, the identifier references that object’s property. When that doesn’t happen, then you’ll be using a global variable (that is, if it exists).

As you can see, with can decrease the readability of your JS code (it may even introduce some bugs in your code). And from a performance stand point, it’s not looking good either because the interpreter needs to do extra work for changing the “context“ within the with block. I tend not to use the with statement in my JS code. In fact, I had completely forgotten it until that I’ve noticed today that it’s used in the JS code that is generated by the new templates “classes” introduced in preview 5 of ASP.NET AJAX (in fact, its side effects introduced a bug in the code I was writing and I didn’t even noticed, but I’ll leave that for a future post).

Stay tuned for more on JavaScript.

4 comments so far

  1. Bertrand Le Roy
    9:35 pm - 9-21-2009

    Yes, with is generally considered harmful and some people are even asking that it be removed from the language. BUT it is essential to Microsoft Ajax client templates in that it enables the current data item to be raised to the scope of the template code, enabling {{ name }} syntax without qualification, whereas otherwise you”d have to do {{ $dataItem.name }} or something like that.

  2. luisabreu
    10:07 pm - 9-21-2009

    Yep, I understand that. Though it might also lead to getting some side effects (ex.: if you misspell the name of a prop and match, say, a global var you won”t get an error; just the wrong result).

  3. Arnis L.
    6:51 am - 9-22-2009

    While reading – thought that i found a Holy Grail too. Too bad…