Hostingheaderbarlogoj
Join InMotion Hosting for $3.49/mo & get a year on Tuts+ FREE (worth $180). Start today.
Advertisement

Null

by
Gift

Want a free year on Tuts+ (worth $180)? Start an InMotion Hosting plan for $3.49/mo.

This post is part of a series called JavaScript Succinctly.
Working With Primitive String, Number and Boolean Values
Undefined

You can use null to explicitly indicate that an object property does not contain a value. Typically, if a property is set up to contain a value, but the value is not available for some reason, the value null should be used to indicate that the reference property has an empty value.

Sample: sample60.html

<!DOCTYPE html><html lang="en"><body><script>

	// The property foo is waiting for a value, so we set its initial value to null.
	var myObjectObject = { foo: null };

	console.log(myObjectObject.foo); // Logs 'null'.

</script></body></html>

Don't confuse null with undefined. undefined is used by JavaScript to tell you that something is missing. null is provided so you can determine when a value is expected but not available yet.


typeof returns null values as "object"

For a variable that has a value of null, the typeof operator returns "object. If you need to verify a null value, the ideal solution would be to see if the value you are after is equal to null. In the following sample, we use the === operator to specifically verify that we are dealing with a null value.

Sample: sample61.html

<!DOCTYPE html><html lang="en"><body><script>

	var myObject = null;

	console.log(typeof myObject); // Logs 'object', not exactly helpful.
	console.log(myObject === null); // Logs true, only for a real null value.

</script></body></html>

Conclusion

When verifying a null value, always use === because == does not distinguish between null and undefined.

Advertisement