If / else Statement with Prompt - javascript

I am super new like day 3 looking and typing code new and I am trying to run this code but it is not working. I have searched and searched but I don't know what I have messed up. Any help would be appreciated.
*note if I take the else away it will run but it does not follow the rule <500 it just says go away to anything you put in.
var budget = prompt('What is your budget?');
if (budget < 500); {
alert('GO AWAY');
}
else (budget >= 500); {
alert('That will do');

It's a else if not else .And remove the ; in if and else statement .
Note*
For your case you have one condition is enough .less 500 second else always match 500 and above.if you have more number of condition you could use elseif
var budget = prompt('What is your budget?');
if (budget < 500) {
alert('GO AWAY');
} else{
alert('That will do');
}

The second check is redundant. And also, you had ; after if and else, remove those:
var budget = prompt('What is your budget?');
if (budget < 500) {
alert('GO AWAY');
} else {
alert('That will do');
}

Instead of using if...else statements is more simple to use Conditional (ternary) Operator and get a variable message out of your logic.
Than call alert(message) only once:
var budget = prompt('What is your budget?'),
message = budget < 500 ? 'GO AWAY' : 'That will do';
alert(message);
Note: the previous answers have well pointed all the errors on the OP.

A couple errors here. Change what you have to this:
var budget = prompt('What is your budget?');
if (parseInt(budget) < 500) {
alert('GO AWAY');
}
else {
alert('That will do');
}
See fiddle
Basically you had a ; after your if statement and after the parenthesis. This is not needed. Also, else does not accept parameters.

var budget = prompt("What's your budget ?");
if(budget < 500) {
alert("GO AWAY");
}
else {
alert("that will do");
}

Related

How to give "No more tries left" in a password-guessing loop

I've just started learning JS and I got stuck here.
What I need to do:
If you don't enter the correct password, you get the message "Try again".
If you don't enter the password 3 times, you get the message "No more tries left".
If you enter the correct password, you get the message "You may enter".
Here's my code:
for ( let i = 3; i > 0; i-- ) {
let password = prompt("What is the password?")
if ( password.toUpperCase() !== "BINGO" ) {
alert("Try again")
} else if ( i = 0 ) {
alert("No more tries left")
} else {
alert("You may enter")
}
}
I can't get it work properly as the message "No more tries left" doesn't show up. I know ( i = 0 ) is wrong but I don't know how to make it work.
Firstly, make sure that you're not using an assignment operator when you check if i == 0. You're currently using i = 0, which doesn't check if the two are equal as much as it assigns the left to the right. No bueno.
Secondly, your for loop is off just by a bit. It'll never get to 0 because you've asked it to loop while i > 0, not i >= 0. But wait - if you use i >= 0, it'll loop four times. That's not what you want either. We'll compromise and loop three times, but check if i == 1 instead of 0.
Here's my corrected code that works:
// loop three times
for ( let i = 3; i > 0; i-- ) {
let password = prompt("What is the password?")
// if it's the correct answer then alert and break the loop
if ( password.toUpperCase() == "BINGO" ) {
alert("You may enter")
break
// if it's not, and the tries has elapsed, then alert and break the loop
} else if ( i == 1 ) {
alert("No more tries left")
break
// if it's not but the tries have not elapsed, then loop again
} else {
alert("Try again")
}
}
Try this.
for ( let i = 3; i >= 0; i-- ) {
if (i===0){
alert("No more tries left");
break;
}
let password = prompt("What is the password?")
if ( password.toUpperCase() !== "BINGO" ) {
alert("Try again")
} else {
alert("You may enter")
}
}
Give the user chance to enter the password 3 times but loop 4 times and check if the loop runs for 4th times(i === 0). if prompt No more tries left and break the loop.
You are using an assignment operator instead of a comparison operator.
Change this:
else if ( i = 0 ) {
alert("No more tries left")
}
To this :
else if ( i == 0 ) {
alert("No more tries left")
}
Try this. It will run the loop until they have entered the password correctly or the number of attempts is 3.
After the loop you can then just check if valid is true or false.
let valid = false;
let attempts = 0;
do
{
const password = prompt('What is the password');
valid = password.toUpperCase() === 'BINGO';
if (!valid && attempts < 2)
{
alert('Try again');
}
attempts++;
} while (!valid && attempts < 3)
if (valid)
{
alert('You may enter');
} else
{
alert('No more tries left');
}
You are asking the user to enter the password in each iteration
using a loop. So, showing that "you don't have anymore attempt left"
is useless here. Because if the value is greater than 3, the
instruction inside the loop will not be executed.
Do not use JavaScript for authentication. It is a client side
programming language and any one who knows how things work can
extract the password. Instead use a back-end language for
authentication such as PHP, Node.js
But if you only want to know about it just for the learning purpose
not because you wanna implement it, the below code will help you
for (let i=0; i<3; i++){
let password = prompt("what is the password: ");
if (password.toUpperCase() != "BINGO"){
alert("Try Again!");
}else{
alert("You may enter!");
i=3;
}
}
There are several ways you can do the "No more attempt left" is, one of the simple and basic is:
<input type="button" value="Enter Code" onclick="checkMe()">
<script>
let i=0;
function checkMe(){
if (i<3){
let password = prompt("Enter password!");
if (password.toUpperCase() != "BINGO"){
alert("Try Again! Attempt "+ (++i));
}else{
alert("You may enter!");
i=3;
}
}else alert("No more attempts left");
}
</script>
The above code can be implemented using input field, as i said, there are several ways. Hope it helps!
Your code is fine, what goes wrong is that it does not fall into the if condition (i == 0), because the loop only runs while i > 0,
just need to adjust like this:
for ( let i = 3; i > 0; i-- ) {
let password = prompt("What is the password?")
if (password.toUpperCase() !== "BINGO" && i > 1 ) {
alert("Try again")
} else if (i == 1 && password.toUpperCase() !== "BINGO") {
alert("No more tries left")
} else {
alert("You may enter")
i = 0
}
}

else statement within nested if statements. How does this code know which else statement to execute?

I get the nested if loops (same as using && operator), but how does this code here know which conditions to execute with no conditions and just back to back else statements? One of them is within the nested if statements. I can tell that's obviously why this works the way it does, I just don't get how. Also, I know how to write this in several more readable ways testing multiple conditions. Please just explain what is happening with this code here. How does it know to output "You are too old" or "You are too young?"
var age = prompt("Please enter Your age here :");
var min_age=18;
var max_age=40;
if(age>=min_age){
if(age<=max_age){
console.log("You meet the requirements for this competition");
}else{
console.log("You are too old");
}
}else{
console.log("You are too young");
}
The if-then-else ambiguity is known for a long time. All languages have solved it by defining that an else will match the first perceding if. So:
if (a)
if (b)
x = 1;
else
x = 2;
resolves to:
if (a) {
if (b) {
x = 1;
}
else {
x = 2;
}
}
EDIT by Nisar's reuest:
The if statement is defined as:
if (<condition>) <statement> [else <statement>]
This means that a <statement> in the above may also be an if statement. So, for example:
if (<condition>) if (<condition>) [else <statement>] [else <statement>]
As each else part is optional, the compiler has no way of knowing when it sees an else part to which if it belongs. To solve that the language defines that an else always matches the first preceding if.
The brackets {} set the limit.
Try to think in pseudocode, look beyond the characters and think about what is happening.
Reading in order:
If you are old enough
If your are not too old
'You meet the requirements for this competition'
OTHERWISE
'You are too old'
END
OTHERWISE
'You are too young'
END
Note how indentation can help see the limits of the conditions. Each indented part can be separated.
Firstly, let's indent your code.
var age = prompt("Please enter Your age here :");
var min_age = 18;
var max_age = 40;
if (age >= min_age)
{
if (age <= max_age)
{
console.log("You meet the requirements for this competition");
}
else
{
console.log("You are too old");
}
}
else
{
console.log("You are too young");
}
Starting off..
var age = prompt("Please enter Your age here :");
Let's say you enter 21 in the prompt box, so age=21
We initialize
var min_age = 18;
var max_age = 40;
Now let's look at the first if condition.
if (age >= min_age)
If you substitute the values,this translates to
if (21 >= 18)
This is true,therefore we go inside the if block and not to the else.
The next line is.
if (age <= max_age)
This translates to
if (21 <= 40)
Considering this is also true, we print You meet the requirements for this competition.
The most important take-away from this is, indent your code, and the rest becomes pretty simple.
There are just 3 Options
too young
correct age
too old
First Check - is the person old enough?
if(age>=min_age)
Second check - is the person too old?
if(age<=max_age)
the only possible option left after this if statment is FALSE :
too old

Working With ifNan Function

I'm having trouble getting the Codecademy section of ifNan done. How do I make it so the ifNan function checks the number I manually input at the end when I run the function. For example:
var isEven = function(number) {
if (number % 2 === 0) {
return true;
} else if (isNan(number)) {
return "Your input is not a number!";
} else {
return false;
}
};
isEven(2);
What would I put in the isNan function so that when I input the number at the bottom it also checks if it is actually a number?
you could condense that down to:
function isEven(number)
{
if(!isNaN(number) || number % 2 === 0)
{
return true;
}
return false;
}
See elclanrs comment. isNan is not a function isNaN is. caps matter there.
So...update to this long-standing issue:
I went back to codecademy and restarted the lesson. After researching for about a week, and a good long breather, I came back to this frustrating issue and even then found myself writing the same exact code that I had in the beginning of this issue (because I knew it was correct).
You all made valid points.
Dennis you're absolutely right this can be condensed in a few areas but Codecademy is very rigid (which I'm liking less and less) so it would have never let me pass the dang section.
Anyways, I wanted to close this but "answer" (kind of) it first.
Thanks for all your assistance.
Try this:
var isEven = function(number) { if (number % 2 === 0) { return true; } else if(isNaN(number) === true || false){ return "your input is not a number"; } else { return false; }// Your code goes here!
}; isEven("Gbemi")

How to fix the expected a identifier

I'm learning JavaScript using the Code Academy website and whenever I try an if / else program it always comes up with expected a identifier. I don't know what I'm doing wrong. My program looks like this:
confirm("Are you ready?")
var age = prompt("What's your age?")
if (age <= 18)
console.log{"You are allowed to play but I take no responsibily";
}
else
{
console.log ;"Have fun playing"
}
To call the console.log function, you will need (round) parenthesis around its argument(s). Also you were missing the opening brace after the if-condition:
confirm("Are you ready?")
var age = prompt("What's your age?");
if (age <= 18) {
console.log( "You are allowed to play but I take no responsibily" );
} else {
console.log( "Have fun playing" );
}
Btw, you can omit the braces if there is only a single statement in the body of an if, else, for, etc. However, it's important to use proper indentation then:
confirm("Are you ready?")
var age = prompt("What's your age?")
if (age <= 18)
console.log( "You are allowed to play but I take no responsibily" );
else
console.log( "Have fun playing" );
Also notice that prompt() is returning a string, which you might want to parse into a number before comparing it against 18:
var age = parseInt( prompt("What's your age?"), 10);
if(confirm("Are you ready?"))
{
var age = prompt("What's your age?");
if (age <= 18)
{
console.log("You are allowed to play but I take no responsibily");
}
else
{
console.log("Have fun playing");
}
}
You need to use proper syntax. console.log for example is console.log("text")
Be sure to have a semi colon after each statement
confirm("Are you ready?")
var age = prompt("What's your age?")
needs to read
confirm("Are you ready?");
var age = prompt("What's your age?");

Count the number of times an input has been made javascript

What is the best practice when counting the number of times an action has been carried out in javascript? for example I have a prompt that asks for a number
var playerGuess = prompt("What is your guess ");
What i would like to do is after 3 attempts end the game with another prompt.
What I am having difficulty with is actually counting the number of inputs
Thanks
I have tried creating a function do count the number of times an input has been made
var guessCount = playerGuess.count;
function limit(playerGuess){
if (guessCount >= 3){
alert("game over");
} else{
alert("carry on");
}
}
totally wrong i know but having a go
Like so:
// Global var to hold number of guesses
var guessCount = 0;
// Function to get the guess
function getGuess() {
// Get a new guess
var guess = prompt('What is your guess ');
// Process guess here, eg:
if (...whatever tests you want to make...) {
// Good guess
alert('Good guess: ' + guess);
} else {
// Bad guess
guessCount += 1;
// Fail out if too many guesses have been tried
if (guessCount >= 3) {
alert('Game over');
return;
}
}
};
Cheers!
You should evaluate the answer you get each time.
If the answer is valid, take the count in another variable and when the count reaches the desired amount take no inputs.
var attempts = 0;
function ask_question(){
if(attempts > 3)
{
// you have played enough!
return;
}
else
{
var playerGuess = prompt("What is your guess ");
if(parseInt(playerGuess) != NaN && playerGuess != '')
{
attempts++;
// do whatever you would like to do with playerGuess
}
}
}
You could do this with a while loop and a variable to store the current iteration. Consider the following, which gives you three chances to guess the "secret" number:
var secretNumber = 42,
youWon = false,
i = 0;
while (i < 3) {
var playerGuess = prompt("What is your guess?");
if (playerGuess == secretNumber){
youWon = true;
break;
}
i++;
}
if (youWon) {
alert("You got it!");
} else {
alert("Sorry, you have no more tries left.");
}
This code loops over and over, incrementing i each time. It asks the question, and checks the answer. If the answer is right, it sets the youWon flag and breaks out of the loop, ending it early. Otherwise, the loop ends naturally after 3 iterations. After the loop is done, the youWon flag is checked to determine if the loop ended because the right answer was given, or if it ended because the number of tries was exhausted.

Categories