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.pngYesterday I showed you how to figure out whether an object had a certain property. But suppose you didn't know ahead of time which property you wanted? Then what you'd want to do is to enumerate all the properties in the object, to see what you've got.

Surely that's beyond anything JavaScript can do, right? Wrong!

If I run this code:


var whazzis = {};
whazzis.who = 'you';
whazzis.why = 'who knows';
whazzis.when = 'back then';
whazzis.where = 'over there';
whazzis.what = 'dunno';

for (var name in whazzis) {
gs.log(name + ': ' + whazzis[name]);
}

I'll get this result:

what: dunno
why: who knows
who: you
where: over there
when: back then

The for (xxx in yyy) statement enumerates all the properties in any object. Inside the for loop, the variable xxx is populated with the current property name being enumerated. What you do with that name inside the loop is completely up to you. In the example above, I simply printed out the value of it.

Some things to keep in mind when using this statement:
  • All properties are enumerated: In particular it doesn't matter what value the property has. Undefined, null, function values — it doesn't matter, they're going to get enumerated.
  • Some properties are notenumerated: I just lied to you. Any property can be flagged as not enumerable. In general, any built-in properties (especially functions, aka methods) are not enumerated. Unless you do something special, any properties your code adds will be enumerable.
  • There is no guaranteed order: Properties can be enumerated in any order. The order may change from browser to browser, from version to version of Service-now's server, or even from one time of day to another. Do not write code that depends on the enumeration order!