The Now Platform® Washington DC release is live. Watch now!

Help
cancel
Showing results for 
Show  only  | Search instead for 
Did you mean: 
SlightlyLoony
Tera Contributor

find_real_file.pngIn JavaScript, "undefined" means two distinctly different things:

  1. A property that doesn't exist.
  2. A property that has the "undefined" value assigned to it.

Huh? Aren't those two ways of saying the same thing? Well…not exactly, and the differences can lead to some unexpected results. Consider this example:


var x = {};
x.s = 'cowabunga';
x.t = undefined;

gs.log('Typeof...');
gs.log('x.s: ' + typeof x.s);
gs.log('x.t: ' + typeof x.t);
gs.log('x.y: ' + typeof x.y);
gs.log('');

gs.log('Direct reading...');
gs.log('x.s: ' + x.s);
gs.log('x.t: ' + x.t);
gs.log('x.y: ' + x.y);
gs.log('');

gs.log('Enumeration...');
for (var n in x)
gs.log('x.' + n + ': ' + x[n]);


If you run this program on a Service-now.com instance, you'll get these results:

Typeof...
x.s: string
x.t: undefined
x.y: undefined

Direct reading...
x.s: cowabunga
x.t: undefined
x.y: undefined

Enumeration...
x.s: cowabunga
x.t: undefined

Notice that x.t shows up in the enumeration, and x.y doesn't? That's because x.t actually has a value — the special built-in value "undefined", which was assigned to it in the third line of the program — but x.y was never assigned at all, so it was never initialized at all.

There's a slightly subtle difference in how various JavaScript platforms handle these two flavors of undefined. On a Service-now.com instance (i.e., server-side JavaScript), this enumeration difference is almost the only difference you'll see. The exception is for properties on the global object. If you run the program below, you'll get a runtime error on the third line, complaining that y is not defined:

var x = undefined;
gs.log('x: ' + x);
gs.log('y: ' + y);

But there was no such complaint in the first program, where we tried to read x.y — in that case the value "undefined" was returned and there was no error.

Browser environments (i.e., client-side JavaScript) most commonly get runtime errors anytime you try to read a property that's never been assigned, but they vary. For example, some flavors of Internet Explorer produce runtime errors for unassigned properties on built-in classes (such as the DOM), but not on pure JavaScript objects.

So the safest thing to do, and a practice I'd recommend, is to write your JavaScript (even for server-side) as though references to unassigned properties would produce an exception. Do this, and you'll never get a nasty surprise...

1 Comment