vendredi 24 avril 2020

Why is "return" needed before randomHull() in the else statement?

The goal of this function is to return a value between 3 and 6. I know there is an easier way to do this, but am just trying to understand how/why this option works.

The below function works, but only if you use return in the else statement. If you do not use "return randomHull()" and instead put just "randomHull()" it will return undefined if the first attempt is not within the range.

My initial understanding was that return was not needed as the value would only be stored if the if statement was true, otherwise it would just run randomHull() again until it passed through the if statement and returned a value within the range.

Why is "return" needed before randomHull() in the else statement?

const randomHull = () => {
     let alienHull = Math.ceil(Math.random() * 6);
     if (alienHull >= 3) {
        return alienHull;
     } else {
        return randomHull();
     }

}

console.log(randomHull());

Aucun commentaire:

Enregistrer un commentaire