Basic help JS

Hi guys, can anyone help me out, please?

Given the below code, can you explain me in details why the console log sort the array from John to Billy and not the reverse? a guy from another forum at the course that i’ll attend in january (I’m a newbie of coding and just started JS :slight_smile: ) answer that: " This code means “put the new name in front of the old names. All you need to to is swapping names[i] and bNames."

Can you explain why though?

thanks a lot!

names = ["Billy", "Ben", "Bob", "John"];
bNames = " ";

for (var i = 0; i < names.length; i+= 1) {
  if (names[i][0]==="B") {
    bNames = names[i] + "  "+bNames;
  }
}

console.log(bNames.trim());

because here:

bNames = names[i] + "  "+bNames;

you prepend the current name. You could insert a console.log to “see” this process happening:

bNames = names[i] + "  "+bNames;
console.log(bNames);

I am not a fan of this approach, I think I would then reverse the loop, and use a mutable data type (array) to store the result.

thanks Stetim, all clear now!

cheers!