0

The codes below works:

var myArray = [];
function myFunc(){
    var randomNumber = Math.floor(Math.random() * 4);
    if(myArray.indexOf(randomNumber) == -1){
        myArray.push(randomNumber);
        console.log(randomNumber); //; didn't use return
    } else {
        myFunc();
    }
}
for(let i=0; i<4; i++){
    myFunc();
}

While the following doesn't, both are almost the same except the following is using "return".

var myArray = [];
function myFunc(){
    var randomNumber = Math.floor(Math.random() * 4);
    if(myArray.indexOf(randomNumber) == -1){
        myArray.push(randomNumber);
        return randomNumber; // using return
    } else {
        myFunc();
    }
}
for(let i=0; i<4; i++){
    console.log(myFunc());
}

The results may not be the same as those are random numbers, please try to refresh it for several times.

I want to use return so that the value could save into the function.

Thanks everyone.

1 Answer 1

2

It returns undefined because you are not returning anything when myArray.indexOf(randomNumber) != -1. Try:

function myFunc(){
    var randomNumber = Math.floor(Math.random() * 4);
    if(myArray.indexOf(randomNumber) == -1){
        myArray.push(randomNumber);
        return randomNumber; // using return
    } else {
        return myFunc();
    }
}
Sign up to request clarification or add additional context in comments.

3 Comments

Thank you very very much Yachay. In the else clause, I just want to run the function again if certain condition is matched. Do you mind to tell me why should I use "return myFunc()" instead of just running the function again? Thanks again
Because, otherwise, when you call "myFunc" again the returned value is lost.
Thank you very much Yachay! Have a nice day.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.