0

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)
1

3 Answers 3

1

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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;

Comments

1

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.

Comments

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.