1

I'm working on an extension for Chrome and I'm just wondering about the usage of "for..in" in Javascript. Let me explain the issue I've found with an example:

Suppose I have a volatile object of the type {prop1: "foo", prop2: "bar", ...}. I want to save this object in a string in a some syntax, e.g., "prop1=foo;prop2=bar;...". Here is the code I used:

var fun = function(data) {
  var str = "";
  for (var i in data) {
    str += i + "=" + data[i] + ";";
  }
  return str;
};
log(fun({x:1, y:2}));

That fun returns the following string: undefinedx=1;y=2;.

I can't really see why it follows this behavior. I know I can use JSON to "stringify" something like this, but actually I just want to understand why it happens.

Finalfire
  • 73
  • 1
  • 2
  • 7

1 Answers1

5

Is that the exact code you're running? The missing + before data[i] leads me to believe it's not. It looks a lot like str is starting off uninitialized, as in:

var fun = function(data) {
  var str;
  for (var i in data) {
    str += i + "=" + data[i] + ";";
  }
  return str;
}
John Kugelman
  • 349,597
  • 67
  • 533
  • 578
  • Yes, it is exactly this, I just fixed typos in the original question. Sorry. Anyway, the code is not working for me, I keep getting the "undefined" in the string. Edit: a simpler code who raises the same behavior is the following: `var a = {x:1, y:2}; for(var i in a) { console.log(a[i]); }` and it logs 1, 2 and then returns (?) undefined. – Finalfire Jul 23 '13 at 21:06
  • 2
    http://stackoverflow.com/questions/11108953/what-does-it-mean-if-console-log4-outputs-undefined-in-chrome-console <-- assuming you're using Chrome, this is the problem(I think it's the same in Firefox and other browsers) – Niccolò Campolungo Jul 23 '13 at 21:14
  • @LightStyle oh well, thank you! I thought it was a strange behavior from the `for..in` loop. – Finalfire Jul 23 '13 at 21:17
  • No, don't worry, it is confirmed by this simple example: `function foo() {return "foo";}`. In console, type `foo()` --> "foo", type `console.log(foo())` --> "foo" and then, new line and undefined. @JohnKugelman I was referring to the last problem Finalfire caught, your answer is right ;) – Niccolò Campolungo Jul 23 '13 at 21:19
  • @LightStyle Ah I follow now. Comment deleted :) – John Kugelman Jul 23 '13 at 22:40