What is ? and : in return

Tell us what’s happening:
Describe your issue in detail here.
i dont understand ? and : in this recursive solution what does it mean?

  **Your code so far**
function sumAll(arr) {
const [first, last] = [...arr].sort((a, b) => a - b);
return first !== last
  ? first + sumAll([first + 1, last])
  : first;
}

sumAll([1, 4]);
  **Your browser information:**

User Agent is: Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/102.0.0.0 Safari/537.36

Challenge: Sum All Numbers in a Range

Link to the challenge:

It’s known as a ternary operator. It’s kind of like an if/else. One of the best tools a developer has is google. Google “MDN ternary”.

1 Like

I just remember that tenary operator has been taught in previous javascript course.Thank you very much for the “MDN ternary” will look for it and will use google more

1 Like

For ease of your understanding, you can read the code as following:

function sumAll(arr) {
const [first, last] = [...arr].sort((a, b) => a - b);

if (first !== last) {
    return first + sumAll([first + 1, last]);
} else {
    return first;
}

sumAll([1, 4]);

Hence you see that this ternary operator (? and : ) is nothing but a shortcut for if-else operation. Unlike if-else blocks, you can use a ternary operator inside an expression. This becomes very useful while working with JSX in the React.js framework.

Happy Learning! :+1: :innocent:

1 Like