So I have been racking my brain why this doesn't work, I am sure that I am over thinking it . So the main thing I am trying is to create a JavaScript function “myGame” which takes game Object and returns some custom message so that when the prompt is left undefined its should say please provide your fav game
My attempt;
let game = prompt('What is your fav game');
function myGame(game){
if(game === undefined){
console.log('Pls provide your fav game');
}else{
console.log(`My fav game is ${game}`)
}
}
myGame(game);
CodePudding user response:
You can directly use like this:
if(prompt('What is your fav game')){
console.log(`My fav game is ${game}`)
}else{
console.log('Pls provide your fav game');
}
If user cancels the prompt, it goes to else block. Alternatively, use if (!prompt()){}
to better implement it checks (user sets the value):
if(!prompt('What is your fav game')){
console.log('Pls provide your fav game');
}else{
console.log(`My fav game is ${game}`)
}
CodePudding user response:
From the prompt()
docs:
Return value
A string containing the text entered by the user, ornull
.
So you'll need to check for null
, not undefined
.
If you press 'ok' right away, the value will be an empty string (''
), so use !game
to check for all false
values
let game = prompt('What is your fav game');
function myGame(game){
if (!game){
console.log('Pls provide your fav game');
} else{
console.log(`My fav game is ${game}`)
}
}
myGame(game);