Kenny
Kenny

Reputation: 153

Javascript - Why sometimes it is "undefined" when using return?

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.

Upvotes: 0

Views: 106

Answers (1)

Yachay J. Tolosa
Yachay J. Tolosa

Reputation: 144

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();
    }
}

Upvotes: 2

Related Questions