Are there significant use cases to assign indefinitely to a variable?

advertisements

There are null and undefined in JavaScript. Are there any meaningful use cases of assigning undefined to a variable?


Yes.

When a property had a value and now you want it to have none, you usually have those choices:

delete:

delete obj.prop;

Problem: it has very big performance impacts. It is one of the biggest performance killers in an otherwise well designed JS program. Track it and be sure to never use it when performance matters (note that the impact isn't just located where you delete the property but also where you read or write other properties of the object later on, including when calling methods).

set the value to null:

obj.prop = null;

This only makes semantic sense when the expected type of the value is "object" (or sometimes "string"). Note that there's a semantic difference between null (i.e. no object) and undefined (i.e. value unset).

set the value to NaN:

obj.prop = NaN;

You won't use this for anything except numbers (but then it can make a ton of sense, depending on the specific use case).

set the value to undefined:

obj.prop = undefined;

This is the best choice in most other cases. It also plays nicely with the usually right way to test whether an argument or argument's property has been set, that is to check options.something === undefined.