简体   繁体   中英

JavaScript Function keeps returning undefined after showing the output

The code answers true or false but after it keeps saying undefined eg trueundefined. What could i have done wrong?

function gamble(){
   let prob = parseInt(prompt('Enter a number'));
   let prize = parseInt(prompt('Enter a number'));
 let pay = parseInt(prompt('Enter a number'));
  let probPrize = prob * prize;
if (probPrize > pay){
  document.write('True');

}else{
  document.write('False');
}

};

document.write(gamble());

You're not returning anything from the function, so it's undefined.

Replace document.write('True') with return 'True' and document.write('False') with return 'False'

because your function gamble doesn't return any value

replace your code to this :

function gamble(){
   let prob = parseInt(prompt('Enter a number'));
   let prize = parseInt(prompt('Enter a number'));
   let pay = parseInt(prompt('Enter a number'));
   let probPrize = prob * prize;
   if (probPrize > pay){
    return 'True';
   }else{
    return 'False';
   }
};
document.write(gamble());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM