Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

Question for :: Build a Quiz Challenge, Part 2 Solution (JavaScript)

Hey, I finish my challenge. But is something wrong with my code, when I run my code is run well, but i have message "undefined". Can someone review it, thanks!

//pertanyaaan disimpan dalam array

var tanya = [
["Siapa nama presiden Indonesia?", "JOKOWI"],
["Siapa manusia pertama yang berhasil mendarat di bulan?","Neil"],
["Siapa nama presiden wanita pertama di Indonesia","Megawati"]    
];

var benar = [];
var salah = [];

//set pertanyaan dengan loop
var no = 0;

while(no < tanya.length) 
{
  var jawab = prompt(tanya[no][0]);
  if(jawab === tanya[no][1]) 
  {
    benar.push(tanya[no][0]);
  } else 
  {
    salah.push(tanya[no][0]);
  }
  no++;

}

//fungsi tampil data yang benar
function tampilData() 
 {
var html;
var no = 0;   
html += "<p>Pertanyaan benar yang anda jawab sebanyak ("+benar.length+")</p>";
html += "<ul>";
   if(benar.length > 0) 
   {
for(no; no < benar.length; no++) 
    {

      html += "<li>"+benar[no];
      html += "</li>";

    }
   }else 
   {
      html += "<li>Upps, sepertinya tidak ada jawaban yang benar!</li>";
   }

   html += "</ul>";

html += "<p>Pertanyaan salah yang anda jawab adalah ("+salah.length+")</p>";
   html += "<ul>";
   if(salah.length > 0)
   {
     for(var no=0; no < salah.length; no++)
     {
       html += "<li>"+salah[no]+"</li>";
     }                     
   }else 
   {
     html += "<li>Uups, sepertinya tidak ada yang salah! <strong>SELAMAT</strong></li>"
   }

   html += "</ul>";

      return html;

 }

function print(message) {
  document.write(message);
}


print(tampilData());

```</script>

#sorry, that code is write in Indonesia language ^-^

2 Answers

Benjamin Barslev Nielsen
Benjamin Barslev Nielsen
18,958 Points

undefined comes from:

var html;

this statement is equal to:

var html = undefined;

And when you concatenate the value undefined with a String, the undefined value is coerced into the string "undefined", so particularly this means:

undefined + "someString" Evaluates to "undefinedsomeString"

Therefore the solution should be to initialize the html variable to the empty String instead:

var html = "";

Hope this helps

Ohh, thanks for replay Sir, it work! xD