-3

I don't understand how does this code work. Can someone point me in the right direction on how to use ? and : in for loops? What do they mean?

var range = function(start, end, step) {
    var arr = [];
    for (var i = start; step > 1 || step === undefined ? i <= end : i >= end; step ? i = i + step : i++) {
        arr.push(i);
    }
    return arr;
};
Udo Klein
  • 6,381
  • 1
  • 31
  • 53
dogpunk
  • 153
  • 1
  • 5
  • [JavaScript conditional operator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Conditional_Operator) – Pointy Jan 11 '15 at 15:32

2 Answers2

0

This is nothing special about for loops. "?" is the ternary operator.

step === undefined ? i <= end : i >= end

evaluates to i <= end if step is undefined, otherwise to i >= end. Or with other words it gives the same result as

(function foo() {
    if (step === undefined) {
        return (i <= end); 
    } else {
        return (i >= end); 
    }
})()

The second use of the ? operator is more tricky as it manipulates the content of i as a side effect. That is the author of this code evaluates the variable step. If it is truthy the i will be advanced by step, otherwise it will be incremented.

Udo Klein
  • 6,381
  • 1
  • 31
  • 53
  • So from what I understand I can use ternary operator as a shorthand for if statements? Is it better to use shorthand properties, or just use if..else? – dogpunk Jan 11 '15 at 16:07
  • @Punkdog it depends; use `?` operator for expressions (assigning variables, etc.) and `if` for statement (run this block of code or the other, no return value). – theonlygusti Jan 11 '15 at 18:45
0

That is just the Conditional (Ternary) Operator.

It's almost shorthand for an if-else statement, in that:

return (boolean expression) ? ifTrue : ifFalse;

is the same as:

if (boolean expression) {
    return ifTrue;
} else {
    return ifFalse;
}

So in your for loop,

step === undefined ? i <= end : i >= end

means:

  1. If step is undefined
  2. The for loop condition (which normally looks like i < length) should be i <= end
  3. otherwise (step is defined) the for loop condition should be i >= end
theonlygusti
  • 7,942
  • 8
  • 40
  • 80