Basic help JS for newbie

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;


1 Like


Maybe a visual execution would help: Click here to visualize the execution of the code on PythonTutor. Click on the buttons First, Last, Next or Prev to see the contents of each variable at a specific point in time :slight_smile:.

1 Like

the console log sort the array

The console is not sorting the array, it’s displaying the bNames variable which is a string.

Basically, on each iteration of the for loop, the code asks:

  • Does the current element start with the character ‘B’?
  • If so, prepend the current element to the variable bNames separated by a space.

The code would do something like this:

  1. First iteration (i equals 0): names[0][0] is equal to 'B'? true, hence bNames = "Billy ".
  2. Second iteration (i equals 1): names[1][0] is equal to 'B'? true, hence bNames = "Ben Billy "
  3. Third iteration (i equals 2): names[2][0] is equal to 'B'? true, hence bNames = "Bob Ben Billy "
  4. Fourth iteration (i equals 2): names[3][0] is equal to 'B'? false, hence bNames doesn’t change.

The last instruction, bNames.trim() just removes trailing spaces from the beginning and the end of the string, meaning bNames equals to Bob Ben Billy.

I hope it helps :slight_smile:.

1 Like

You’re a star mate! I was not looking further than my nose and couldn’t wrap my head around it!

thanks a lot!

1 Like