akmur
akmur

Reputation: 1635

For... of loop returning unexpected undefined

I am doing a simple for...of loop. I do not understand why I get different results when I console.log the output of the loop and when I print it to screen.

const list = document.getElementById('list');
const results = [1, 2, 5];
let listItems;

for (let r of results) {
  listItems = listItems + `<li>${r}</li>`;
  console.log(r);
}

list.innerHTML = listItems;

//// console.log returns 1, 2, 5

//// in the DOM, i get undefined, 1, 2, 5

You can try it in my codepen.

Thanks for your help.

Upvotes: 0

Views: 64

Answers (4)

Tim Consolazio
Tim Consolazio

Reputation: 4888

Because letItems is undefined the first time. It only has a value the second time around, after you set it in the loop.

Do this:

let listItems = '';

Upvotes: 0

Paweł Lula
Paweł Lula

Reputation: 310

It's because listItems is undefined, and when you add a string 'foo' to variable which is undefined the result is 'undefinedfoo`.

Correct version is below:

const list = document.getElementById('list');
const results = [1, 2, 5];
let listItems = '';

for (let r of results) {
   listItems = listItems + `<li>${r}</li>`;
   console.log(r);
}

list.innerHTML = listItems;

Upvotes: 1

BenM
BenM

Reputation: 53198

Because in the first iteration of the loop, listItems is undefined. Give it an empty string:

let listItems = '';

Updated CodePen

Upvotes: 2

Oriol
Oriol

Reputation: 288020

That's because listItems in initially undefined.

let listItems;
console.log(listItems); // undefined

Initialize it to the empty string, or use array joining:

let listItems = '';
for (let r of [1, 2, 5])
  listItems += `<li>${r}</li>`;
console.log(listItems);

listItems = [];
for (let r of [1, 2, 5])
  listItems.push(`<li>${r}</li>`);
console.log(listItems.join(''));

Upvotes: 4

Related Questions