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
CodePudding user response:
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.
CodePudding user response:
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;