0

Beginner here. So I was practicing using For loops to generate an array containing the combination of the data within 2 different arrays (firstName & lastName) into another array (fullNameArray) as shown below:

let firstName = ["John","Maria","Brandon","Gaby"];
let lastName = ["Stewart","Rambeau","Waffel","Sinclair"];
let fullNameArray=[];


function fullName (array1,array2){
    let temp;
    for (let i=0;i<array2.length;i++){
       temp=array1[i]+" "+array2[i];
       fullNameArray.push(temp);
       
    };
};

fullName(firstName,lastName);
console.log(fullNameArray);

This code will give what i wanted : ['John Stewart','Maria Rambeau','Brandon Waffel','Gaby Sinclair']

But what i'm curious about is that i previously used return inside the For loop. I wrote it like this:

function fullName (array1,array2){
    let temp;
    for (let i=0;i<array2.length;i++){
       temp=array1[i]+" "+array2[i];
       return fullNameArray.push(temp);
       
    };
};

and it only shows ['John Stewart'].

Does this mean that using return in a loop will terminate the ENTIRE looping process and go through it just once?

  • 4
    yes, but it doesn't just terminate the loop, it returns from the function it is called in as well so nothing after the loop will be executed either. If you just want to stop the loop see [break](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/break) – pilchard Jul 02 '22 at 14:51
  • wow. `return` is pretty aggressive. Okay, thank you so much for answering! – Juan Yeremia Jul 02 '22 at 14:54
  • https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/return – VLAZ Jul 02 '22 at 14:54

0 Answers0