Case study #2 undefined initialization

airportyh and I are currently working on an ES3-based implementation of ES5 array extras. As such, we are trying to conform as much as we can to the chapter 15.4.4 ES5 conformance suite.
With this suite comes a testing library sth.js. After throwing this library into jslint. I saw that there are variable initializations to undefined. This is bad for two reasons.
I explain what to do with object properties in a third part.

If you don’t want to define it, don’t do it

By default, the value of a variable that is not initialized is undefined

var a;
alert(a); // alerts "undefined"

There is no trap, no ambiguity, no inconsistency. This behavior exists since the big bang.

undefined‘s value may not be undefined

var undefined = 5; // No error, no mistake, no joke.
var a = undefined;
alert(a); // alerts '5'

Quite scary. In the weirdest cases where the code you write is wrapped (to be made private, for instance), it could be in an environment where undefined is overridden.

Getting rid of an object property

Once again, assigning undefined is not the good idea.
Two solutions : if you want to keep the property in the object, but get rid of the value, assign to null (you cannot do the previous assignment trick with null). If you want to remove the property from the object, use delete on this property.

Note : delete removes a property from an object. It doesn’t “delete” an object from the memory. I will write an article about delete sooner or later

Conclusion

My conclusion is simple : never initialize to undefined. There is no reason for it and it might be dangerous.

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