Search code examples
arraysfor-loopalertnested-loops

can you explain what this javascript code does?


var fName = ["Sean", "Niel", "Patt", "Jimmy", "John", "Sam"];
var lName = ["Paker", "Hamilton", "Shaker"];
var fullName = [];
var f = 0;
for (var i = 0; i < fName.length; i++) {
  for (var j = 0; j < lName.length; j++) {
    fullName[f] = fName[i] +" " + lName[j];
    f++;
  }
}
alert(fullName[0]);

Can you explain what is going on on this code?


Solution

  • This code creates a list of combinations of the first names given in fName with the last names given in lName. The two loops, loop through the list elements and concatenate the two strings to form 6*3 combinations. To be precise:

    fullName[0] = "Sean Paker"
    fullName[1] = "Sean Hamilton"
    fullName[2] = "Sean Shaker"
    fullName[3] = "Niel Paker"
    fullName[4] = "Niel Hamilton"
    ....
    

    and so on

    Finally there is an alert(pop up) to show fullName[0] which is "Sean Paker"