change
var html; // default value is undefined
to
var html=''; //set value as empty string
Question
The first printed result of this code return 'undefined'. Why? And what would be the proper implementation to avoid it?
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');
Solution
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');
NOTE: At first your variable html
had no value, so it was considered like undefined