Can't get function to print on its own, and log method manually prints undefined and wanted value

Viewed 22

The code:

const goodfortunes = [
  ' You will be rich',
  ' You will live a long life', 
  ' Wednesday looking lucky',
  ' You have good luck today'
]
    
let randnum = () => Math.floor(Math.random() * 8);

let randphrase = () => {
    if (randnum() === 0) {
        console.log(goodfortunes[0])
    }else if (randnum() === 1) {
        console.log(goodfortunes[1])
    } else if (randnum() === 2) {
        console.log(goodfortunes[2])
    } else if (randnum() === 3) {
        console.log(goodfortunes[3])
    }
}
console.log(randphrase())

can't get console.log to print goodfortunes index value unless manually logging randphrase(). When manually logging randphrase() it prints an undefined value along with one of the wanted indexes. Anyone know why?

1 Answers

You got a Undefined Value because you are actually trying to log a function. You already logged your goofortune value inside the randphrase.

To print your value, you should only go for

randphrase()

instead of

console.log(randphrase())

Also, if you only attempt to log goodfortunes strings, adjust your randnum like this to avoid out of bound index.

let randnum = () => Math.floor(Math.random() * goodfortunes.length);

And finally, call once randnum().

The final code shoud look like this :

const goodfortunes = [' You will be rich', ' You will live a long life', 
' Wednesday looking lucky', ' You have good luck today']
const badfortunes = [' You will die in 7 days', ' You have bad luck', 
' You will be poort', ' Look out on Tuesday']

let randnum = () => Math.floor(Math.random() * goodfortunes.length);

let randphrase = () => {
    var myNumber = randnum()
    if (myNumber === 0) {
         console.log(goodfortunes[0])
    }else if (myNumber === 1) {
        console.log(goodfortunes[1])
    } else if (myNumber === 2) {
        console.log(goodfortunes[2])
    } else if (myNumber === 3) {
        console.log(goodfortunes[3])
    }
}
randphrase()

Related