For loops a bit confusing

For loops a bit confusing
0.0 0

#1

im here again, seeking for help :confused:

Look at this code:


function pairwise(arr, arg) {
  

  return arr.reduce(function(acc, next, index, array){
    
   for (var i = index + 1; i<arr.length; i++); {

    if(array[index] + array[i] === arg) {

        acc += index + i; 
    
        array[index] = array[i] = NaN; 
    
}

  }

      return acc; 


}, 0);


}

pairwise([1,4,2,3,0,5], 7);

THE RESULT IS 11…I was told, that for loops stops, when the IF statement is true, so in this case 3+4 = 7 ,which is true, so how come the loop continues to loop?

Here is the case, when it stops looping:

function findElement(arr, func) {
  
  for (i = 0; i < arr.length; i++) {
    if (func(arr[i])) {
      return arr[i];
    }
   
  
}  
 }

findElement([1, 2, 3, 4], function(num){ return num % 2 === 0; });

THE RESULT IS 4


#2

Add a break; statement inside the if block. The break statement (as the name suggests) breaks out of a loop prematurely.

By the way, the program logic seems slightly weird. Can you tell us what the challenge is?


#3

If I properly indent your for loop (see below), there is nothing to stop the for loop. The for loop only stops iterating once your for loop’s condition (i.e. i < arr.length) is no longer true.

		for (var i = index + 1; i < arr.length; i++);
		{
			if (array[index] + array[i] === arg) {
				acc += index + i;

				array[index] = array[i] = NaN;
			}
		}

In the 2nd for loop example (seen below), the return statement is what breaks out of the for loop. In fact a return statement will break out of the calling function all together.

  for (i = 0; i < arr.length; i++) {
    if (func(arr[i])) {
      return arr[i];
    }
  }  

If you want to stop iterating inside a for loop or while loop, you can use the break keyword as @n-kartha has suggested.


#4

#1 EXAMPLE:

Given an array arr, find element pairs whose sum equal the second argument arg and return the sum of their indices.

If multiple pairs are possible that have the same numeric elements but different indices, return the smallest sum of indices. Once an element has been used, it cannot be reused to pair with another.

For example pairwise([7, 9, 11, 13, 15], 20) returns 6. The pairs that sum to 20 are [7, 13] and [9, 11]. We can then write out the array with their indices and values.

7 + 13 = 20 → Indices 0 + 3 = 3
9 + 11 = 20 → Indices 1 + 2 = 3
3 + 3 = 6 → Return 6

#2 EXAMPLE:

Create a function that looks through an array (first argument) and returns the first element in the array that passes a truth test (second argument).
findElement([1, 3, 5, 8, 9, 10], function(num) { return num % 2 === 0; }) should return 8.

Just to make everything clearer


#5

hm yeah but in the #2 example, we have an array [1, 2, 3, 4] and only 4 is returned and not 2? how come?

findElement([1, 2, 3, 4], function(num){ return num % 2 === 0; });

Both 2 and 4 are equal to 0


#6
function findElement(arr, func) {
	for (i = 0; i < arr.length; i++) {
		if (func(arr[i])) {
			return arr[i];
		}
	}
}

findElement([1, 2, 3, 4], function(num) {
	return num % 2 === 0;
});

When I run the above code, only 2 is returned and not 4. Why? Because when findElement is called with the array and the anonymous function as arguments, the findElement function iterates through arr until the following if statement evaluates to true. The very first time it evaluates to true, the applicable value is returned and the findElement function is exited and does not continue to execute.

if (func(arr[i])) { 

In the second iteration of the for loop, i = 1, so arr[1] is 2. The anonymous function gets the value 2 and since 2 % 2 === 0 is true, you return the value true back to the if statement, so since the if statement evaluates to true, the return statement (return arr[1]) is executed, so only the value 2 gets returned.


#7

yes thats what i was thinking, and thats why i was comparing those two example, but i didnt know it has to do with the RETURN statement, so i was confused why the #1 example keeps on looping, when it already found a truthiness, but now it goes on and finds another one. Okay thank you, it makes a bit more clearer.


#8

Okay one more question…For example i want to return both numbers (2, 4) how could i rewrite this?
I tried it like this, but it says undefined -->

function findElement(arr, func) {
  var nums = [];
  for (i = 0; i < arr.length; i++) {
    if (func(arr[i])) {
      nums.push(arr[i]);
    }

return nums;
   
  
}  
 }

findElement([1, 2, 3, 4], function(num){ return num % 2 === 0; });

#9

it returns an empty array basically


#10

ok i did it! had to move my “return nums” a bit down…


#11

Your latest attempt above returns an empty array, because in the first iteration of the for loop, the func(arr[0]) returns false, because 1 % 2 !== 0 and then after the if statement you return nums so the function immediately exits and the empty array referenced by nums is returned.


#12

it works now

function findElement(arr, func) {
  var nums = [];
  for (i = 0; i < arr.length; i++) {
    if (func(arr[i])) {
      nums.push(arr[i]);
      
    }
    
      
   
  
}  

 return nums;
 }

findElement([1, 2, 3, 4], function(num){ return num % 2 === 0; });

#13

You really should properly indent your code to make it more readable. For example:

function findElement(arr, func) {
	var nums = [];
	for (i = 0; i < arr.length; i++) {
		console.log(func(arr[i]));
		if (func(arr[i])) {
			nums.push(arr[i]);
		}
	}
	return nums;
}

findElement([1, 2, 3, 4], function(num) {
	return num % 2 === 0;
});

Otherwise, it is more difficult to figure out where the if statement or for loop ends.