-1

I am trying to learn javascript and was going through this code. In the function function range(start, end, step = start < end ? 1 : -1), what does step = start < end ? 1 : -1 stand for?

function range(start, end, step = start < end ? 1 : -1) {
  let array = [];

  if (step > 0) {
    for (let i = start; i <= end; i += step) array.push(i);
  } else {
    for (let i = start; i >= end; i += step) array.push(i);
  }
  return array;
}

function sum(array) {
  let total = 0;
  for (let value of array) {
    total += value;
  }
  return total;
}

console.log(range(1, 10))
// → [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
console.log(range(5, 2, -1));
// → [5, 4, 3, 2]
console.log(sum(range(1, 10)));
// → 55
talemyn
  • 7,822
  • 4
  • 31
  • 52
  • It's the [conditional operator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Conditional_Operator). It's used in a [default parameter](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Default_parameters) expression, but otherwise it works exactly as you'd expect. – p.s.w.g May 20 '19 at 17:28

2 Answers2

0

It means:

let step 
if(start < end) step=1
else step=-1
Milad Jafari
  • 1,135
  • 1
  • 11
  • 28
0

It is called ternary operator. It basically means if start < end evaluates to true then assign 1 to step otherwise -1

This line step = start < end ? 1 : -1 can be written as

if(start < end){
 step=1;
}
else{
step=-1
}
brk
  • 48,835
  • 10
  • 56
  • 78