Question

Description of Problem (Fiddle):

The first printed result of this code return 'undefined'. Why? And what would be the proper implementation to avoid it?

Code:

var animals = {
    dogs: 0,
    cats: 0,
    birds: 0,
    fish: 0
};

function countAnimals(animal) {
    animals[animal]++;

    var html;
    for (var key in animals) {
        if (animals.hasOwnProperty(key)) {
            html += key + ': ' + animals[key] + '<br/>';
        }
    }

    $('#output').html(html);
};

countAnimals('dogs');
Was it helpful?

Solution

Fiddle Demo

change

var html; // default value is undefined

to

var html=''; //set value as empty string

OTHER TIPS

var animals = {
    dogs: 0,
    cats: 0,
    birds: 0,
    fish: 0
};

function countAnimals(animal) {
    animals[animal]++;

    var html = ""; // here define variable as a string
    for (var key in animals) {
        if (animals.hasOwnProperty(key)) {
            html += key + ': ' + animals[key] + '<br/>';
        }
    }

    $('#output').html(html);
};

countAnimals('dogs');

JSFiddle

NOTE: At first your variable html had no value, so it was considered like undefined

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top