How to fix the expected a identifier - javascript

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?");

Related

why does "Number" make the "else if" work here?

I have a task to play a little with if/else if.
i don't understand why, when I write my code like the example below, the "else if(age === 18)" part doesn't work. it shows up as "undefined". the other 2 work.
But, when i add (Number(age) at all of them, it works. Why is that? why can i use 2/3 without "Number", but i need it to use 3/3?
var age = prompt("Please type your age!");
if (age < 18) {
alert("Sorry, you are too young to drive this car. Powering off");
} else if (age === 18) {
alert("Congratulations on your first year of driving. Enjoy the ride!");
} else if (age > 18) {
alert("Powering On. Enjoy the ride!");
}
You need to convert the string to a number. The easiest way is to take an unary plus +.
With a number, you can check with a strict comparison Identity/strict equality operator === against a number, because you have at least the same type.
var age = +prompt("Please type your age!");
if (age < 18) {
alert("Sorry, you are too young to drive this car. Powering off");
} else if (age === 18) {
alert("Congratulations on your first year of driving. Enjoy the ride!");
} else {
alert("Powering On. Enjoy the ride!");
}
prompt returns a string, which cannot be strictly equal to the number 18 since the types are different. It would work, however, if you used loose equality (==).
The simplest way to convert it to a number would be to use the unary plus operator, which has much the same function as the Number function.
var age = +prompt("Please type your age!");
It is because prompt returns a string.
The operators < and > will allow you to compare a string to a number, by pre-converting the string to a number and then comparing them. Read this article for more info on this, called "Type Coersion" in JS.
The === operator however will not do this type coercion/conversion, it will directly compare "18" with 18 and return false.
To fix this, you can instead use the other equals operator, ==, which does include type coercion.
However, a better way of doing it would be to check the input is definitely a number, like this:
var age = Number(prompt("Please type your age!"));
if (Number.isNaN(age)) {
alert("Try again with a number");
} else if (age < 18) {
alert("Sorry, you are too young to drive this car. Powering off");
} else if (age === 18) {
alert("Congratulations on your first year of driving. Enjoy the ride!");
} else if (age > 18) {
alert("Powering On. Enjoy the ride!");
}
cause prompt returns a stirng.
But < & > operators converts string to a number
var age = prompt("Please type your age!");
if (age < 18) {
alert("Sorry, you are too young to drive this car. Powering off");
} else if (age === '18') {
alert("Congratulations on your first year of driving. Enjoy the ride!");
} else if (age > 18) {
alert("Powering On. Enjoy the ride!");
}

If / else Statement with Prompt

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");
}

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

I need someone to look over some javascript code for me because I'm getting an error that says syntax error

I need someone to look at this code. I am a beginner at javascript and I can't find the error(s) in this code I made.
var user = prompt ("Are you a goblin, knight, troll, human, or wizard?").toLowerCase()
var name = prompt("What is your name?").toLowerCase()
var gender = prompt("Are you male or female?").toLowerCase()
switch(user) {
case 'goblin':
console.log("Hello, you are going to have a fun journey as a goblin");
var meetAnt = prompt ("You run into a giant ant eater, you can attack or run. Do you choose to attack?").toLowerCase()
if(meetAnt = yes) {
console.log ("you stab him in the eye, but then he hits you with his trunk. You are injured");
var finishAnt = prompt("you can either risk your life and finish him, or try to run away. Do you finish him?").toLowerCase()
if(finishAnt = yes) {
return true;
console.log("congratulations you have killed the aint eater!")
}
else if(finishAnt = no) {
return false;
console.log("You run away and barley make it, you are badly hurt");
else {
console.log("sorry thats not an option")
}
}
}
else {
return true;
console.log("You run past the ant eater and get to saftey. You are very lucky")
}
break;
case 'knight':
console.log("Hello, you are going to have a fun journey as a knight");
var dayFight = prompt("You are versing the goblins in a fight, you need to choose how many days you go to fight(1-100). Remember if you choose too little days then you won't have stayed long enough to win the fight but if you stay to long you have more of a chance of dying or getting injured").toLowerCase()
if(dayFight < 40) {
return false;
console.log("You did not fight enough days, which has resulted in your kingdome loosing the war to the goblins.");
}
else if(dayFight > 60) {
return false;
console.log("You have went to war to long and been seriously injured.");
}
else if(40<=dayFight=>60) {
return true;
console.log("You have been at war for the right amount of time. You have came out of the war with no injuries and you also have defieted the goblins!")
}
break;
case 'troll':
console.log("Hello, you are going to have a fun journey as a troll");
var red = true;
var green = true;
var yellow = false;
var blue = false;
var houseRaid = prompt("You see four huts in the middle of the woods. You can raid two. There is a red hut, blue hut, yellow hut, and green hut. What is one color house that you want to raid?").toLowerCase()
var doorPick = prompt("Do you want to enter throuhg the back door or front door?").toLowerCase()
if(doorPick||houseRaid = "red"||"green" && "back door") {
return true;
console.log("You raided these houses and left before any villagers would see you");
}
else {
return false;
console.log("You raided those houses, but one of them was a booby trap and you are now captured");
}
break;
case 'human':
console.log("Hello, you are going to have a fun journey as a human");
var reinforceFound = prompt("You know a storm is comming and you have to reinforce your hut, but you only have enough material to reinforce either your lower foundations or higher foundations. Which do you inforce? Higher or lower?").toLowerCase()
if(reinforceFound = lower) {
return false;
console.log("The storms winds pushed down the top of your house and caved in your roof.");
}
else if(reinforceFound = higher) {
return true;
console.log("The storm did not do that much damage to your house due to your reinforced higher foundations. Good choice");
}
else {
console.log("sorry but that is not an option. Pick either 'higher', or 'lower'")
}
break;
case 'wizard':
console.log("Hello, you are going to have a fun journey as a wizard");
var blood = true;
var dust = true;
var wings = false;
var mushrooms = false;
var postion = prompt("You are working on a new healing potion but you do not know what you need to add to finish it. You have 4 ingrediants; blood, dust, wings, mushrooms. Pick one too add. (WARNING: Pick carefully because if you choose the wrong ingerdiant, then your potion will be ruined.)").toLowerCase()
if(postion = wings || mushroom) {
console.log("You picked a bad ingrediant and now your potion is ruined.");
}
else if(postion = dust || blood) {
console.log("you picked the right ingrediant and your potion is okay")
}
else {
console.log("sorry but that is not an option");
}
break;
default:
console.log("Sorry but that is not a character in the game");
};
I am making this code for a lesson in the website www.codecademy.com. It is supposed to be a small part of a game. Sorry there is so much, I couldn't narrow down anymore were the error is coming from.
The syntax error is because you are missing an ending bracket at line 18 (of the posted code). This:
else {
should be:
} else {
The missing bracket means that there is no matching if before the else.
Some other problems in the code, but perhaps not all of them:
You are missing semicolons at the end of many statements. They are not required when the statement ends where the line ends, but they are recommended.
You have a problems with comparisons like these:
if(meetAnt = yes) {
The comparison operator is == (or ===), and you are missing delimiters around the string value, so it would be interpreted as a variable name. It should be:
if(meetAnt == "yes") {
In comparisons like these you get unexpected results:
if(dayFight < 40) {
The variable contains a string, so the value 40 is converted to the string "40" for the comparison, and they are compared as strings instead of numbers. That means that for example "100" < "40". You should parse the input string to a number:
dayFight = parseInt(dayFight, 10);
With comparisons like this the syntax is wrong:
else if(40<=dayFight=>60) {
Comparing one value using two operators doesn't work, and there is no => operator. You need two conditions:
else if(40 <= dayFight && dayFight <= 60) {
In comparisons like this you have used the || operator wrong (and the wrong comparison operator and the missing string delimiters):
if(postion = wings || mushroom) {
It's used between conditions, not to compare multiple values in one condition:
if(postion == "wings" || postion == "mushroom") {
When you put a statement after return, that statement will not be executed as the code exits the function at the return statement:
return true;
console.log("congratulations you have killed the aint eater!")
Reorder them:
console.log("congratulations you have killed the aint eater!")
return true;

Age verification, ensure is not blank and not less than 18

it is supposed to make sure that the first 2 elem[0] and elem[1] are not blank and if they are to return and error or display the name
the second part is to give an error if the age, elem[2] is less than 18
function checkForm()
{
var elem = document.getElementById('myForm').elements;
if(elem[0].value or elem[1].value ==(""))
{
alert("Please enter your first and last name");
}
alert("Your name is " + elem[0].value + "" + elem[1].value);
if number(elem[2].value) < 18
{
alert("You are to young to be playing on this computer.");
}
alert("Your age is "+ elem[2].value);
}
looks like you aren't formatting your if() statements correctly.
instead of 'or', you should use || (two pipe symbols).
Also, correct format for the statement:
if(condition){
what to do if 'condition' is true
}
so, correct format:
if(elem[0].value =="" || elem[1].value ==""){
alert("Please enter your first and last name");
}
alert("Your name is " + elem[0].value + "" + elem[1].value);
use this formatting for your other code as well.
Your first conditional
if(elem[0].value or elem[1].value ==(""))
This error in this line stems from a colloquialism in English: when you say "the cat or the dog is here", this is a shortcut for the proper English, which is "the cat is here, or the dog is here".
Programming languages usually don't have colloquialisms; your code evaluates elem[0].value, then performs a boolean "or" operation on it with the expression elem[1].value == ("") as the other comparator.
That is, your line is equivalent to:
if ((elem[0].value) or (elem[1].value == ""))
and I think it's clear that this was unintended.
You probably meant to write:
if (elem[0].value == "" || elem[1].value == "")
Note that I've also replaced the non-existent or with ||, which means "or".
Your second conditional
In this line:
if number(elem[2].value) < 18
You forgot the surrounding ().
So:
if (number(elem[2].value) < 18)
Though it's not clear what you meant by number. Further study the text that instructed you to write that.
Other notes
Your indentation is generally messy.
I hope you are enjoying learning JavaScript. Keep reading your book and studying the syntax, because you generally have to get it precisely right: details matter!
try:
if (!isNaN(number(elem[2].value)) // its a number?
{
if (number(elem[2].value) < 18) // add ()
{
alert("You are to young to be playing on this computer.");
}
alert("Your age is "+ elem[2].value);
}

Categories