Forbidden words in JavaScript

JavaScript has 3 forbidden words –

  • With
  • In
  • Eval

Eval is generally understood to perform poorly and to be unsafe. But what’s so bad about ‘with’ and ‘in’?

With

It is sort of a quirk with JavaScript where the scope of an operation changes when you use “with”. As with a few things in programming it is not that they can’t be used but they are often used badly. In JavaScript we are accustomed to the scope of “global” and functions. So a variable used in one function can’t be accessed by another function, right? Well when you use “with” you’re in ANOTHER scope, the scope of the thing you’re using. Let me explain.

Imagine you create a wipe function. It takes a cloth object and wipes a table. After you wipe a dirty table the cloth sadly becomes dirty. In JavaScript you could say –

You can run this code in a browser console to see the results. If you look at this simple program at the end the cloth is clean but it is not blue, what happened? We were supposed to be in the scope of the “cloth” object which is how we set its property to clean but something weird happened and we couldn’t set the cloth’s colour. Uh oh! We ran into problems because the colour property was defined but JavaScript usually lets us define properties on the fly.

As you can see, there are some cases where you might want to use “with” but it can also lead to bugs which are unexpected and so difficult to debug. There’s a thread on Stackoverflow about it. My point of view is along the lines of what Alan Storm says.

In

My opinion is as a result of coming across a bug a long while ago. I remember trying to use “in” to iterate over some DOM nodes because I thought it was cool but strange things kept happening and I was lost as to why so I used another method. Much later I read about how it walks up the prototype chain (with respect to DOM nodes it’s a bit more complicated than that). That’s why it’s evil. Again, not because it is “wrong” but it causes more problems than it solves so it is better to avoid it and do what I know is going to work the way I want it to work.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s