0

This is a range function that takes 3 arguments start of the array, end of the array, and step,

If no step is given, the elements increment by one, corresponding to the old behavior.

What does the first link talk mean? This part (... step = start < end ? 1 : -1)

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
Usitha Indeewara
  • 870
  • 3
  • 10
  • 21
bardala
  • 51
  • 7
  • What don't you understand? – Ryan Zhang Jul 31 '22 at 02:37
  • 1
    Does this answer your question? [How do you use the ? : (conditional) operator in JavaScript?](https://stackoverflow.com/questions/6259982/how-do-you-use-the-conditional-operator-in-javascript) – PM 77-1 Jul 31 '22 at 02:38
  • Also, https://stackoverflow.com/questions/894860/set-a-default-parameter-value-for-a-javascript-function – PM 77-1 Jul 31 '22 at 02:39
  • I dont understand that 'step = start < end ? 1 : -1' – bardala Jul 31 '22 at 02:41
  • 1
    @Jscoder it's a default parameter value which is also a conditional. So for example you can do `function range(a,b,c)` but maybe you want to make `c` optional. `function range(a,b,c = 4)` does that - `range(1,2);` will be as if you called `range(1,2,4);`. – Luke Briggs Jul 31 '22 at 02:47

2 Answers2

1

That is a simple usage of a ternary operator. It acts like an if in javascript. If you want to learn more about ternary operator here is the link:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Conditional_Operator.

Actually if you don't use ternary operator there, this line:

step = start < end ? 1 : -1

should look like this:

if(start < end) step = 1;
else step = -1;
Emin Begic
  • 13
  • 5
0

step is a default parameter that assigns value from a condition. It is something similar to this:

if(start < end) {
        step = 1;
} else {
        step = -1;
}

That type of conditions are called ternary operators. Learn more about that: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Conditional_Operator

Hope this helps.

Usitha Indeewara
  • 870
  • 3
  • 10
  • 21