I am looking to debug this code. I want a prompt window to show and ask for myAge. YourAge is defined as 25. After I enter any age in the prompt window, I want an alert to show message ‘I am older than you with n numbers’, another alert to show ‘You are older than me with n numbers’ and a third alert to show ‘Your age is the same as mine - 25’ in accordance with what age I have entered.
It seems that the function is entering both of the two first alerts one after another…and if I add the else part, then it is asking for a declaration or statement.
<!DOCTYPE HTML>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,height=device-height,initial-scale=1">
<title>Untitled document</title>
</head>
<body>
<!--NOTE: removed inline event handler -->
<button>try it</button>
<script>
(function(d) {
'use strict';
/* NOTE: added the event listener */
d.querySelector('button').addEventListener('click', comparison, false );
function comparison() {
/* NOTE: swapped myAge and yourAge around */
let myAge = 25;
/*NOTE window. is not required */
let yourAge = prompt('Please enter your age', '');
/* NOTE: removed the ; from between the if statement and the { */
if ( myAge > yourAge) {
/* NOTE: window. is not required */
confirm('I am older than you by ' + (myAge - yourAge) + ' years');
}
/* NOTE: else statement added */
else {
/* NOTE: removed the ; from between the if statement and the { */
if ( myAge < yourAge) {
confirm('Your are older than me by ' + (yourAge - myAge) + ' years');
}
else {
confirm('Your age is the same as mine - 25');
}
}
}
}(document));
</script>
</body>
</html>
BTW note that prompt() will always return a string; so it’s a good idea to explicitly cast it to a number, rather than relying on JavaScript’s (somewhat obscure) automatic type coercion:
const myAge = Number(window.prompt('Please enter your age', ''))
// Check if the enetered age is a valid number
if (Number.isNaN(myAge) {
window.alert('Please enter a valid number')
return
}
Thank you @m3g4p0p. When I changed the let myAge=Number(window.prompt('Please enter your age', ''));
It solved the problem that it was showing only the correct alert message according to the typed value in the prompt. However it was also showing the alert message for ‘Your age is the same as mine 25’. I changed the if (myAge===yourAge){ window.confirm('Your age is the same as mine 25'); }
and it works. I don’t know why it doesn’t work with else or if else.