Can someone explain Array Iteration to me?

I decided to take a full-stack web developer bootcamp on Udemy because even though I really like freeCodeCamp and think it’s a great resource for practice and learning, I wanted a more guided approach that is a bit more compact.

But for the life of me, I am hung up on this Array problem set. I just can’t seem to wrap my head around how to create loops to check things in arrays.

Here’s my code:

//printReverse()

/*var vowls = ["a", "e", "i", "o", "u"];

console.log(vowls);

var vowls = vowls.reverse();

console.log(vowls[i]);*/

function printReverse(vowls){
  for(var i = vowls.length-1; i >=0; i--){
    console.log(vowls[i]);
  }
}
  

printReverse(["a","e","i","o","u"]);

//isUniform([1,1,1,1,1,1,1,1,1]);
/*var isUniform = [1,1,1,2,1,1,5,1,1,1];


for(var i = 0; i < isUniform.length; i++) {
	if(i != 1){
		return false;
	}
	return true;
} */

var isUniform = [1,1,1,2,1,1,5,1,1,1];


isUniform.forEach(function(num) {
	if(num != 1){
		return false;
	}
  return true;
});

What I am trying to do with the vowels is print them backwards, but I ended up borrowing some code from the internet for that. With isUniform, I’m trying to check if each number in the array is in fact the number 1, but it either always gives me back an error, or “undefined” when I test it in the dev tool console on Google Chrome.

Return statements do not work as you expect them to in the forEach method. Plus, even if they did, you would stop iterating after only the first iteration.

If your goal is to print out true if an element of the array is a number and false if an element of the array is not a number, then you could use the forEach and just use a console.log statement to display the value to the console.

I tried what you said, and it counted, but it’s kind of weird in how it did it.

var isUniform = [1,1,1,2,1,1,5,1,1,1];


isUniform.forEach(function(num) {
	if(num != 1){
		console.log(false);
	}
  console.log(true);
});

3VM909:8 true
VM909:6 false
3VM909:8 true
VM909:6 false
4VM909:8 true
undefined

I expected it to count 8 trues and two falses, but it counted 10 trues and two falses.

I went ahead and watched the solution, and honestly, I don’t know how I would have figured it out on my own.

function printReverse(arr){
	for(var i = arr.length - 1; i >= 0; i--){
      console.log(arr[i]);
	}
}

printReverse([3,6,2,5]);

My code looked similar, but I didn’t think of having to count backwards by starting at the end of the array, and subtracting from the variable [i].

You have a console.log statement below your if statement code block which will always display true to the console which is why you see true displayed 10 times.

1 Like
var isUniform = [1,1,1,2,1,1,5,1,1,1];


isUniform.forEach(function(num) {
	if(num != 1){
		console.log(false);
	}
	else if(num == 1){
        console.log(true);
	}
  
});

Yeah that was the problem. Thank you!

You know right you could just console.log(i === 1), right?