Reputation: 35
I'm trying to write a simple javascript code to generate a random door (either door1 or door2, and if door1 is generated, the phrase 'you win' appears.
Right now, despite if door1 or door2 is generated, the output is still 'you lose'. What am I doing wrong?
let doors = ["door1", "door2"]
function selectDoor() {
const randomDoor = doors[Math.round(Math.random())]
console.log(randomDoor)
}
if(selectDoor() === "door1") {
console.log('you win')
} else {
console.log('you lose')
}
Upvotes: 0
Views: 39
Reputation: 295
You should return the value in the function
let doors = ["door1", "door2"]
function selectDoor(){
const randomDoor = doors[Math.round(Math.random())]
console.log(randomDoor);
return randomDoor;
}
if(selectDoor() === "door1"){
console.log('you win')
} else {
console.log('you lose')
}
Upvotes: 1
Reputation: 119827
You're not returning randomDoor
from selectDoor
.
function selectDoor(){
const randomDoor = doors[Math.round(Math.random())]
console.log(randomDoor)
return randomDoor
}
Returning nothing is equivalent to returning undefined
which is a falsy value, effectively a false
when used with comparison operators.
Upvotes: 1