0
0
Javascriptprogramming~20 mins

Return inside loops in Javascript - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Return Loop Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
What is the output of this code with return inside a for loop?

Look at the function below. What will testReturn() output when called?

Javascript
function testReturn() {
  for (let i = 0; i < 5; i++) {
    if (i === 2) {
      return i;
    }
  }
  return -1;
}
console.log(testReturn());
A4
B2
C0
D-1
Attempts:
2 left
💡 Hint

Remember that return immediately exits the function.

Predict Output
intermediate
2:00remaining
What does this function return?

What will the function findFirstEven return?

Javascript
function findFirstEven(arr) {
  for (const num of arr) {
    if (num % 2 === 0) {
      return num;
    }
  }
  return null;
}
console.log(findFirstEven([1, 3, 5, 6, 8]));
A1
B3
Cnull
D6
Attempts:
2 left
💡 Hint

The function returns the first even number it finds.

Predict Output
advanced
2:00remaining
What is the output of this nested loop with return?

What will this function output when called?

Javascript
function nestedReturn() {
  for (let i = 0; i < 3; i++) {
    for (let j = 0; j < 3; j++) {
      if (i + j === 3) {
        return i * j;
      }
    }
  }
  return -1;
}
console.log(nestedReturn());
A2
B3
C0
D-1
Attempts:
2 left
💡 Hint

Check when i + j === 3 happens first and what i * j is then.

Predict Output
advanced
2:00remaining
What happens if return is inside a forEach loop?

What will this code output?

Javascript
function testForEach() {
  [1, 2, 3].forEach(num => {
    if (num === 2) {
      return num;
    }
  });
  return 'done';
}
console.log(testForEach());
A2
BTypeError
Cdone
Dundefined
Attempts:
2 left
💡 Hint

Remember that return inside forEach only exits the callback, not the outer function.

🧠 Conceptual
expert
3:00remaining
Why does return inside a loop behave differently in forEach vs for-of?

Consider these two functions:

function a(arr) {
  for (const x of arr) {
    if (x > 0) return x;
  }
  return null;
}

function b(arr) {
  arr.forEach(x => {
    if (x > 0) return x;
  });
  return null;
}

Why does a([1,2,3]) return 1 but b([1,2,3]) returns null?

ABecause return inside forEach only exits the callback, not the outer function
BBecause for-of loops do not support return statements
CBecause forEach automatically returns the first truthy value
DBecause return inside forEach throws an error
Attempts:
2 left
💡 Hint

Think about what return does inside a callback function vs a loop.