Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

For loop nested within a for loop

Hello!

I am trying to understand how the following code words; can anyone please explain it to me keeping in mind that I am a beginner? Thanks!!

x=[-1,-2,3,-4,-5];

for(var j = 0; j<x.length; j++){
  for(var i=0; i<x.length-1; i++){
    if(x[i]<0){
      var temp = x[i];
      x[i] = x[i+1];
      x[i+1] = temp;
    }
  }
}

for(var g=x.length-1; g>=0; g--){
  if(x[x.length-1] <0){
  x.pop();
  }
}

console.log(x);

2 Answers

have added comments to each line..

for(var j = 0; j<x.length; j++){   // this is the outer loop.. it will loop 5 times
  for(var i=0; i<x.length-1; i++){  // for each of the outer loop.. this will run 4 times.. so in total 4*5
    if(x[i]<0){  // this is checking if current value i.e. x[0] which is -1 is less than 0 
      var temp = x[i];  // create a temporary variable
      x[i] = x[i+1];  // make the temp var = the NEXT element in the x in this case it will be -2
      x[i+1] = temp;  // set the value of next element equal to the temp variable
    }
  }
}

Hi shez azr,

You had the 3 backticks correct but there needs to be a blank line before your opening 3 backticks. I went ahead and fixed your code formatting for you.

shez azr:

Here's a tip that I just learned from one of the instructors when adding code to a comment or an answer;

Wrap it with this

' ' '[syntax type] [code here] ' ' '

Use the offhand quote that is just under the ~ symbol on your keyboard. Also, [syntax type] is html or javascript or php. whatever the code type is.

This will help your answers be more coherent. Good answer though. :)

don't include the brackets [], though.