Geronimo
Geronimo

Reputation: 57

Code returns 'undefined"

Why is this piece of code returning undefined ?

http://jsfiddle.net/hdy3grgj/

function getMoods(nb) {
        var index;
        var moods;
        var a = ["MOOD0001", "MOOD0002", "MOOD0003", "MOOD0004", "MOOD0005", "MOOD0006", "MOOD0007", "MOOD0008", "MOOD0009", "MOOD0010", "MOOD0011", "MOOD0012", "MOOD0013", "MOOD0014", "MOOD0015", "MOOD0016"];
        for (index=0; index<=nb; ++index) {
                if(index==0 || index==4 || index==8 || index==12) { moods += '<div class="col-xs-4">'; }
                        moods += 
                                '<div class="checkbox">'
                                    +'<label for="'+a[index]+'">'
                                        +'<input type="checkbox" id="'+a[index]+'" class="moods"> '+a[index]
                                    +'</label>'
                                +'</div>';
                if(index==3 || index==7 || index==11) { moods += '</div> '; }
        }
        $("#moods-area").html(moods);
}
getMoods(12)

Upvotes: 0

Views: 45

Answers (3)

David Thomas
David Thomas

Reputation: 253308

Because the initial value of moods is undefined, as it was never itialized (declared, yes; initialised, no); changing:

var moods;

to:

var moods = '';

There is no 'undefined': JS Fiddle demo.

Upvotes: 1

Felix Kling
Felix Kling

Reputation: 816242

The initial value of moods is undefined. See what happens when I add a string to an uninitialized variable:

> var foo;
> foo + 'bar';
"undefinedbar"

Solution: Initialize the variable with an empty string.

Upvotes: 1

orhanhenrik
orhanhenrik

Reputation: 1415

You get the "undefined" in the beginning of your string because you are not setting a value for moods, and the adding a string to it. It will then convert moods to a string, which turns out "undefined", and add some content to it. To fix this, use var moods=""; instead of var moods;

Upvotes: 1

Related Questions