JavaScript Quickie: Setting a variable to undefined defines it (sorta)

Worked this out while answering a Stack Overflow question, and thought it was worth sharing.

Basically, assigning anything, including undefined to a variable or property will bring it into existence. This probably doesn’t matter all that often, but it can cause a sparse array to not be all that sparse.

arr = [42,69,,66];

arr.hasOwnProperty('0'); // returns true, because arr[0] == 42
arr.hasOwnProperty(''2'); // returns false, because that element doesn't exist
arr.hasOwnProperty('3'); // returns true

alert(arr[2]); // will alert 'undefined'
arr[2] = undefined;
alert(arr[2]); // still alerts 'undefined'

arr.hasOwnProperty('2'); // now returns true, as it now exists

delete arr[2];

arr.hasOwnProperty('2'); // returns false, because it no longer exists

The Point: Just because a variable or property is undefined, doesn’t mean it isn’t taking up some space. To be sure, you need to check and delete it if it exists.

Notes

  1. codelahoma posted this