I don't get this piece of javascript code, can you help me and explain it?

function rangeOfNumbers(startNum, endNum) {
  return startNum === endNum
    ? [startNum]
    : [...rangeOfNumbers(startNum, endNum - 1), endNum ];
}

Hello there,

Depending on what you are struggling to understand here are some elements of that function:

  1. Recursion - Explained at length here: Replace Loops using Recursion -1 explanation
  2. Ternary Operator - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Conditional_Operator
  3. Spread Operator - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax

Hope those help. If you do not understand anything specific, mention it, and we will try to go in more depth.

1 Like