1

So, I am a beginner in JavaScript and I was just playing around by creating some functions! why does if returned there is a different answer and why does if console logged there is a different answer!

SO IF I CONSOLE LOG THIS

const ex = (arra1) => {
  for (let i = 0; i < arra1.length; i++) {
    console.log(arra1[i]);
  }
};
ex([1, 2, 3]);

answer for the above function is 1 2 3

BUT IF RETURN THIS

const ex = (arra1) => {
  for (let i = 0; i < arra1.length; i++) {
    return arra1[i];
  }
};
console.log(ex([1, 2, 3]));

But the answer for this above function is 1

Alec
  • 8,529
  • 8
  • 37
  • 63
  • 1
    `return` immediately terminates the function execution, so you only get one iteration from the loop. – VLAZ Jan 05 '21 at 08:29
  • `return` will terminate the function execution, thus it terminates the loop aswell – Naren Jan 05 '21 at 08:29
  • There's always good reading on MDN: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/return – Cat Jan 05 '21 at 09:04

3 Answers3

1

return will stop the execution immediately. As per MDN,

When a return statement is used in a function body, the execution of the function is stopped. If specified, a given value is returned to the function caller.

Md Sabbir Alam
  • 4,937
  • 3
  • 15
  • 30
1

In the first example you are not returning anything but just logging the each value of the array.

console.log(arra1[i]);

In the second example you are just using return in the loop so in the first iteration the function will return a value which is first element of array. return statement just ends the further execution of the function.

Maheer Ali
  • 35,834
  • 5
  • 42
  • 73
1

return terminates the function and the loop, stopping after the first iteration

In the first example you don't terminate anything, so you end up iterating over everything

Alec
  • 8,529
  • 8
  • 37
  • 63