LNA
LNA

Reputation: 1447

Simple 'for' loop to create divs

Why am I getting an 'undefined' at the top?

http://jsfiddle.net/oybz69xy/1/

var tiles;
function populateTiles(limit) {
for (var i=0; i< limit; i++) {
    tiles += "<div class='tile'>Tile</div>";
}
}
populateTiles(4);

$('#container').html(tiles);

<div id="container">


</div>

Upvotes: 0

Views: 124

Answers (4)

Manivannan
Manivannan

Reputation: 3254

You can use array, instead of using concatenation in loop, refer below code which will improve the performance when the loop size is more

var tiles = [];
function populateTiles(limit) {
for (var i=0; i< limit; i++) {
    tiles.push("<div class='tile'>Tile</div>");
}
}
populateTiles(4);

$('#container').html(tiles.join(''));

<div id="container">


</div>

Upvotes: 1

jz1108
jz1108

Reputation: 1308

Because the initial value of variable tiles is undefined. When an undefined value plus a string the string format of that value is used and that is the string "undefined". So you need to change your code to this;

var tiles = "";

Upvotes: 1

musical_coder
musical_coder

Reputation: 3896

Remember that the += operator really means that

tiles += "<div class='tile'>Tile</div>";

gets expanded to

tiles = tiles + "<div class='tile'>Tile</div>";

The problem is that on the first loop iteration, tiles is undefined (because you haven't assigned anything to it), so you're concatentating undefined with a string. That's what's causing the behavior that you're seeing.

Initialize tiles to "" first.

Upvotes: 3

peterjb
peterjb

Reputation: 819

Because you are using += on an undefined variable. If you first line is var tiles = ""; that should do the trick.

Upvotes: 2

Related Questions