0

I have the following code...

function foo(type) {
    if(foo.type == undefined) foo.type = 0;
}

What I'd like it to do is create a new property on the foo object for each "type" that comes through and set that property to zero (and later begin counting each time a "type" comes through). However, I hit a mental blip, in this case foo.type is probably evaluated as the property type, on foo and not whatever the variable type refers to.

I need to convert the value of type to a property, any ideas?

And yes I know this question's name sucks, if you think of something better just edit the quesiton.

Cody Smith
  • 2,732
  • 3
  • 31
  • 43

2 Answers2

3
function foo(type) {
    if(foo[type] == undefined) foo[type] = 0;
}

You probably want to use === undefined so you won't get any unexpected results

Community
  • 1
  • 1
nicosantangelo
  • 13,216
  • 3
  • 33
  • 47
  • Oh wow, thanks! I looked for this on W3C, no mention what-so-ever in the JS object, array or variable lessons. – Cody Smith Jul 17 '13 at 00:34
  • 1
    `var a = null; console.log(a == undefined);` – zerkms Jul 17 '13 at 00:35
  • `var a = null, undefined = 'not Im defined'; console.log(a === undefined);` ;-) – zerkms Jul 17 '13 at 00:37
  • Ok, that's fair but, really? redefining undefined? – nicosantangelo Jul 17 '13 at 00:37
  • 2
    @NicoSantangelo: well, you cannot be sure in anything when you use 3rd party plugins or whatever. It silly indeed, but still possible :-) – zerkms Jul 17 '13 at 00:38
  • @zerkms: Third party plugins can't redefine `undefined` in any modern browser. The only shared scope is the global, and `undefined` isn't writeable. –  Jul 17 '13 at 00:48
  • @Crazy Train: if you combine files before minification (as we all do) - it's easy to get http://jsfiddle.net/xULxd/ – zerkms Jul 17 '13 at 01:04
  • 1
    @zerkms: Your code example is running in a `window.onload` handler, so it's not global. You're right that if you combined all files, and wrapped the entirety of them in a function, then you could shadow the global `undefined`, but that would be an odd thing to do. http://jsfiddle.net/xULxd/1/ –  Jul 17 '13 at 01:56
2
if (typeof foo[type] === 'undefined') {
    foo[type] = 0;
}
zerkms
  • 249,484
  • 69
  • 436
  • 539