Javascript - How to use null

20 November 2020, 7:45 am by antelove19


Sources:

Oreilly Head First JavaScript Programming 1


How to use null

There are many functions and methods out there in the world that return objects, and you’ll often want to make sure what you’re getting back is a fullfledged object, and not null, just in case the function wasn’t able to find one or make one to return to you. You’ve already seen examples from the DOM where a test is needed:

var weather = document.getElementById("weatherDiv");
if (weather != null) {
    // create content for the weather div
}

Keep in mind that getting null doesn’t necessarily mean something is wrong. It may just mean something doesn’t exist yet and needs to be created, or something doesn’t exist and you can skip it. Let’s say users have the ability to open or close a weather widget on your site. If a user has it open there’s a

with the id of “weatherDiv”, and if not, there isn’t. All of a sudden null becomes quite useful:

var header = document.getElementById("header");
if (header == null) {
    // okay, something is seriously wrong if we have no header
}

If the result of getElementById isn’t null, then there is such an element in the page. Let’s create a nice weather widget for it (presumably getting the weather for the local area).

Remember, null is intended to represent an object that isn’t there.


  1. Oreilly, "Oreilly Head First JavaScript Programming", page 271 



Keywords:


Video not yet
0 comment