user3366240
user3366240

Reputation: 85

javascript ternary operator error

I am confused when the ternary operator behaves differently than I expected. Here is my code:

function zeroCol() {
    var arr = []
    for (var i = 0; i <= 5; i++) {
        (i % 2 == 0) ? arr.push(0) : arr.push(1)

        return arr.join(" ")
    }
}
console.log(zeroCol())

It prints 0 instead of 01010 that I expected. But that works using if/else,why?

if(i%2==0) arr.push(0) 
arr.push(1);

Upvotes: 0

Views: 134

Answers (3)

user1636522
user1636522

Reputation:

Make your life easier, remove it :

function zeroCol() {
    var arr = [];
    for (var i = 0; i <= 5; i++) {
        arr.push(i % 2);
    }
    return arr.join(" ")
}

Notice that return stops the function, so, put it outside of the for loop.

To build on dfsq's comment, notice that this function is useless in its current state. Indeed, the loop's limit and the divisor are both hard coded. Consequently, we already know its result : "0 1 0 1 0 1". It could be more interesting to allow the user to pass these values as parameters to the function, like so :

function zeroCol(divisor, howMany) {
    var arr = [];
    for (var i = 0; i < howMany; i++) {
        arr.push(i % divisor);
    }
    return arr.join(' ')
}

Usage examples :

zeroCol(2, 4) // "0 1 0 1"
zeroCol(3, 4) // "0 1 2 0"
zeroCol(4, 4) // "0 1 2 3"

Upvotes: 2

mayabelle
mayabelle

Reputation: 10014

Your issue is not with the operator; you are returning inside the loop, so it's returning after the first iteration through the loop. Place your return statement outside the loop:

function zeroCol(){
    var arr=[]
    for (var i=0;i<=5;i++){
        (i%2==0) ? arr.push(0) : arr.push(1);
    }

    return arr.join(" ");
}
console.log(zeroCol());

Upvotes: 0

9er
9er

Reputation: 1734

It seems as though you return after the first iteration of your for loop. That might be why it only prints 0. It only executes the ternary operator once.

Upvotes: 2

Related Questions