mep
mep

Reputation: 67

For loop doesn't show my range

I'm trying to get my for loop to show every number between 47 to 28 in order highest to lowest.

For some reason my code gives me the answer "28, 28".

Can anyone help me se what I've done wrong? I just want to add that I'm still very new to javascript!

    var fx = "";

    var printRangeReversed = function(rangeStart1,rangeStop1){
        for (var a3=rangeStart1; a3 > rangeStop1; a3--); 
            fx+=a3+",";
            return fx=rangeStop1&&(fx+=a3),fx;
            return fx = fx.substr(0,fx.length-1);
    }

ANSWER = printRangeReversed(47,28);

Upvotes: 0

Views: 54

Answers (2)

Chris Montgomery
Chris Montgomery

Reputation: 2354

You don't want to do a return inside the loop. Let it finish, then return the result. For example:

var printRangeReversed = function(rangeStart1,rangeStop1){
    var fx = "";
    for (var a3=rangeStart1; a3 > rangeStop1; a3--) {
        fx+=a3+",";
    }
    return fx;
}

ANSWER = printRangeReversed(47,28);

Upvotes: 0

Amit Joki
Amit Joki

Reputation: 59262

The for loop ends with a ;, so the subsequent line is just executing as if it were outside the loop. Also, the second return statement is redundant, as the code below the first return is unreachable.

A better code would be

var fx = "";
var printRangeReversed = function(rangeStart1,rangeStop1){
    var arr = [];
    for (var a3 = rangeStart1; a3 >= rangeStop1; a3--) 
        arr.push(a3);
    return arr.join(); // same as arr.join(",")
}
fx = printRangeReversed(47, 28);

Note, that I've used >= instead of just >, as it isn't what you want.

Upvotes: 6

Related Questions