0

I am studying Javascript, for loop, and trying to put the same elements from two different arrays to another new array. It will print two common elements when I put 'console.log()' outside of For loop, However, if I put 'return console.log()' in if statement, it won't work properly(it shows only [ 'Ray' ].)

I would like to know the difference between them.

I will leave two codes for you. Thank you so much for your help.


//code1
let bobsFollowers = ['Natalia', 'Ray', 'Kay', 'Clau'];
let tinasFollowers = ['Ray', 'Yama', 'Kay'];
let mutualFollowers = [];

for(let i = 0; i< bobsFollowers.length; i++){
  for (let j = 0; j< tinasFollowers.length; j++){
    if (bobsFollowers[i] === tinasFollowers[j]){
       mutualFollowers.push(bobsFollowers[i])

    }
  }
}

 console.log(mutualFollowers)//output: [ 'Ray', 'Kay' ]


//code2
let bobsFollowers = ['Natalia', 'Ray', 'Kay', 'Clau'];
let tinasFollowers = ['Ray', 'Yama', 'Kay'];
let mutualFollowers = [];

for(let i = 0; i< bobsFollowers.length; i++){
  for (let j = 0; j< tinasFollowers.length; j++){
    if (bobsFollowers[i] === tinasFollowers[j]){
       mutualFollowers.push(bobsFollowers[i])
return console.log(mutualFollowers)     
    }
  }
}// output: [ 'Ray' ]
Nagisa Ando
  • 285
  • 5
  • 19
  • maybe you are interested in some more advance tackling of this problem: https://stackoverflow.com/questions/37320296/how-to-calculate-intersection-of-multiple-arrays-in-javascript-and-what-does-e – Nina Scholz Nov 06 '19 at 15:13

3 Answers3

1

A return keyword breaks the current function execution and returns a value. If you use it in the loop, it will break it as soon as it's executed. This is basically the direct reason for that.

More explanation: If you do return console.log(mutualFollowers);, then the console.log() is evaluated first, and the result of that is passed to the return which returns it from the current function. The result of console.log() is undefined so your main function will also return undefined.

Sebastian Kaczmarek
  • 8,120
  • 4
  • 20
  • 38
0

well of course... return statements stops the execution of the function you're in, meaning it also breaks the for loop you're in.

In your case, it gets to the return only after finding the first mutual follower, which is Ray, so it breaks the function and prints only ['ray'].

BTW, because your return is on the console.log(), it actually return out of the function the result of the console.log() operation, which is undefined.

Gibor
  • 1,695
  • 6
  • 20
0

The keyword return exits the current function, in javascript, but not only. Most programming languages work like this.

So when it processes 'Ray', it quits the function without processing the next ones.

Vincent
  • 3,945
  • 3
  • 13
  • 25