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

Here's a little test of your JavaScript knowledge. Can you figure out what the script below will print?


var a = [];
var b = {};
b['a'] = 0;
b['b'] = 1;
b['c'] = 2;
a[b.a] = new String('hamburger');
a[b.b] = null;
a[b.c] = 'bogus';
var x = a[1];
if (x)
   gs.print(a[2]);
else
   gs.print(a[0]);

Drill in for the answer (and an explanation):

A tasty "hamburger" should be your reward. Here's why...

The line var a=[]; creates a new instance of an Array; it's exactly the same thing as var a = new Array();.

The line var b={}; creates a new instance of an Object; it's exactly the same thing as var b = new Object();.

The lines like b['a'] = 0; assign numerical values to the named properties of the Object instance in "b" (this line assigns the numerical value "0" to property "a" in the Object instance in "b").

Confused yet?

The lines like a[b.a] = new String('hamburger'); assign values to numbered elements of the Array instance in "a". This line assigns the value new String('hamburger') (which is the string "hamburger") to the array element 0 (because b.a contains 0).

If you follow all the logic above, then the value of a[1] is null, and this gets assigned to x. Then in the if (x), JavaScript will coerce the value of x to a boolean. A null value coerces to a boolean false. So the else clause will be executed, and the value of a[0] will be printed (and thus you get your tasty hamburger).

The coercion to boolean is worth understanding in some detail, as a mistake here can get you in trouble. The rules are that all values will coerce to a boolean true except these:
  • a boolean false
  • a numeric 0
  • an empty string
  • a null
  • an undefined