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
Jennifer Hughes
11,421 PointsFor 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
shezazr
8,275 Pointshave 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
}
}
}
Joel Smith
14,779 Pointsshez 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. :)
Joel Smith
14,779 Pointsdon't include the brackets [], though.
Jason Anello
Courses Plus Student 94,610 PointsJason Anello
Courses Plus Student 94,610 PointsHi 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.