Why this function gave me the undefined in javascript?

I am newbie to the javascript and I wrote the simple function below.
I am wonder that the function blow gave me the undefined. Is there any mistake in the function below?

function randFace() {
    return ["crown", "anchor", "heart", "spade", "club", "diamond"]
    [rand(0, 5)];
}

console.log(randFace())

32 thoughts on “Why this function gave me the undefined in javascript?”

  1. Since it is not clear what is the rand in your problem does.

    Thus, in JavaScript, there is a function called random() that generates a random number between 0 and 1.

    To generate the random index for the given array we need to have values between 0 and 6.

    Since Math.random generated the value between 0 and 1, we need to multiply that value with the arr.length.

    const arr = ["crown", "anchor", "heart", "spade", "club", "diamond"];
    function randFace() {
        let rand = Math.floor(Math.random() * 6);
        
        return arr[rand];
        
    }
    
    console.log(randFace())
    Reply
  2. Undefined error is occurring because there is no rand() function. i believe that you want to get a random string from the array using the function. I have altered your code little bit to get the expected output. Try it to see if this is what you want

    function getRandomInt(min, max) {
      min = Math.ceil(min);
      max = Math.floor(max);
      return Math.floor(Math.random() * (max - min) + min); //The maximum is exclusive and the minimum is inclusive
    }
    function randFace() {
        return ["crown", "anchor", "heart", "spade", "club", "diamond"]
        [getRandomInt(0, 5)];
    }
    
    console.log(randFace())
    Reply
  3. It is simple code using javscript

        const value= ["crown", "anchor", "heart", "spade", "club", "diamond"]
        var random = Math.floor(Math.random() * value.length);
     console.log(value[random]);
    
       
    Reply
  4. function randFace() {
    var faces= ["crown", "anchor", "heart", "spade", "club", "diamond"]
    return(faces[Math.floor(Math.random() * 5)]);
    }
    
    console.log(randFace())
    

    I think this is what you are looking for.:)

    Reply
  5. rand() is an incorrect method in javascript.

    You will get your desired output by the following code.

    function randFace() {
        return ["crown", "anchor", "heart", "spade", "club", "diamond"]
        [Math.floor(Math.random()*5+1)];
    }
    
    console.log(randFace())
    

    You can refer more about random in W3 Schools.

    Reply
  6. Try this,

    function randFace() {
        let faces = ["crown", "anchor", "heart", "spade", "club", "diamond"]
        return faces[Math.floor(Math.random() * faces.length)];
    }
    
    console.log(randFace())
    
    Reply

Leave a Comment