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

Why doesn't the code run this alert statement in the loop?

var animals=["horse", "ox", "cow", "pig", "duck"];
var i = 0;
while (i < animals.length) {
  console.log(i);
  console.log(animals.slice(i, i + 1));
  if (animals.slice(i, i + 1) === "pig") {
    alert("Found it");
    break;
  }
 i++;
}

Edited by jason chan for formatting.

1 Answer

Hi Aaron,

So your code above looks like (or it did before Jason sorted out the formatting :-) )

var animals=["horse", "ox", "cow", "pig", "duck"]; 
var i = 0; 
while (i console.log(i); 
console.log(animals.slice(i, i + 1)); 
if (animals.slice(i, i + 1) === "pig") { 
  alert("Found it"); 
  break; 
} 
i++; 
}

To get it to run I changed it to

var animals=["horse", "ox", "cow", "pig", "duck"]; 
var i = 0; 
while (i < animals.length){
  console.log(i);
  console.log(animals.slice(i, i + 1));
  if (animals.slice(i, i + 1) == "pig") { 
    alert("Found it"); 
    break; 
  } 
  i++; 
} 

Your while statement needed a condition that can be evaluated. So I checked i against the length of the animals array.

Then you were missing the opening { after the while statement.

Then lastly is the line "if (animals.slice(i, i + 1) === "pig")"'. slice creates a new array, so what it is actually evaluating to is 'Array [ "pig" ]', not just "pig". So when you then try and use the strict equality test (===) it is returning false, as 'Array [ "pig" ]' is not the same as "pig". Instead you can use the loose equality test (==), which will look at the content of the array and decide that it's close enough.

Hope that's helped.