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 JavaScript Loops, Arrays and Objects Tracking Multiple Items with Arrays Using For Loops with Arrays

Aakash Srivastav
seal-mask
.a{fill-rule:evenodd;}techdegree
Aakash Srivastav
Full Stack JavaScript Techdegree Student 11,638 Points

reversing array with for loop

Why doesn't initializing n within the for loop reverse the order of array elements. My code is-

var lotOfNames = ["Aakash" , "Shubham" , "Ankit" , "Shanu"];
function reverseArray( newArray ){

    for( let i = 0 ; i < Math.floor(n/2) ; i++){
                var n = newArray.length;
        let temp = newArray[i];
        newArray[i] = newArray[n-i-1];
        newArray[n-i-1] = temp;
    }
    return newArray;
}
console.log(reverseArray(lotOfNames));

When I run this code . It prints the same array. But when I initialised n outside for loop , function works and it print the reverse order of elements as expected. I know its silly to do such thing. But i was just experimenting with the code.

1 Answer

Steven Parker
Steven Parker
231,269 Points

The loop depends on the value of "n" in the condition clause ("i < Math.floor(n / 2)"). So if "n" is not established before the loop starts, then the condition is false to start with and the loop does not run.