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.

6
  • 3
    Except for two syntax errors(typos, I guess) the code is working to me. Commented Jul 23, 2013 at 20:54
  • @LightStyle Three if you count the missing ; at the end of fun's initialization, but semicolon insertion masks that one. ;) Commented Jul 23, 2013 at 20:56
  • Well that's not exactly a thrown syntax error :P Commented Jul 23, 2013 at 20:57
  • Correct. I consider it an error, the same way I consider accidental or sloppy global variable use an error. (But of course the parser does not.) Commented Jul 23, 2013 at 20:58
  • consider using JSON.stringify() instead of hand-packing objects into strings for later use... Commented Jul 23, 2013 at 21:00

1 Answer 1

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;
}
Sign up to request clarification or add additional context in comments.

5 Comments

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.
stackoverflow.com/questions/11108953/… <-- assuming you're using Chrome, this is the problem(I think it's the same in Firefox and other browsers)
@LightStyle oh well, thank you! I thought it was a strange behavior from the for..in loop.
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 ;)
@LightStyle Ah I follow now. Comment deleted :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.