wyc
wyc

Reputation: 55283

Why is the following for loop not printing anything?

ages = {paul: 11, rick: 7 }

for n,a in ages
  console.log("names: #{n}, ages: #{a}")

So nothing is being printed in the console. What I'm doing wrong?

Upvotes: 1

Views: 52

Answers (1)

Bill the Lizard
Bill the Lizard

Reputation: 405815

That translates into the following JavaScript:

var a, ages, n, _i, _len;

ages = {
  paul: 11,
  rick: 7
};

for (a = _i = 0, _len = ages.length; _i < _len; a = ++_i) {
  n = ages[a];
  console.log("names: " + n + ", ages: " + a);
}

Note that it's trying to loop through the ages object using the length property, which doesn't exist.

Change your script so the loop uses for n,a of ages syntax instead (relevant documentation), and your code translates into valid JavaScript and prints to the console.

var a, ages, n;

ages = {
  paul: 11,
  rick: 7
};

for (n in ages) {
  a = ages[n];
  console.log("names: " + n + ", ages: " + a);
}

Upvotes: 3

Related Questions