I was doing some basic Javascript and I wanted to pass some variables into a function. There appears to be a couple of ways to check for nulls in Javascript - 'null' and 'undefined'. At first glance, they seem to be the same, but dig deeper and they are different.
Scratching about the web revealed some useful information...
To check for a variable which as been explicitly set to null, use this:
if (varname == null)
To check if a variable exists, use this:
if (typeof(varname) != 'undefined')
If you know the variable exists, but want to check if it has a value assigned to it, use this:
if (varname != undefined)
If you want to know if an object contains a variable regardless of whether the variable has a value assigned to it or not, use this:
if ('membername' in object) // With inheritance
if (object.hasOwnProperty('membername')) // Without inheritance
No comments:
Post a Comment