I'm teaching myself JavaScript using Code Academy and I'm trying to make some simple code so that when prompt asks a question, the user reply gives a response.
example.
prompt says "what's your favourite colour?"
user says "blue"
response "that's the same colour as the sky!"
But when I try to add different options, I get Syntax error: unexpected token else.
I tried making it so that if I asked a question, the reply gets a response but anything else gets a response.
Here's the code.
prompt("what do you want?");
if ("coke");
{console.log ("no coke, pepsi.")};
else
console.log ("pepsi only.")};
If anyone has any ideas, I'd be very grateful!
This error can occur for a number of reasons, but is typically caused by a typo or incorrect code. Luckily, the SyntaxError: Unexpected token error is relatively easy to fix. In most cases, the error can be resolved by checking the code for accuracy and correcting any mistakes.
The JavaScript exceptions "unexpected token" occur when a specific language construct was expected, but something else was provided. This might be a simple typo.
Tokens: These are words or symbols used by code to specify the application's logic. These include +, -, ?, if, else, and var. These are reserved by the JavaScript engine and cannot be misused. They also cannot be used as part of variable names.
Disclaimer: I don't work for Coca Cola.
You need to save the return value of prompt
if you want to use it later. Also, you have some syntax errors that should be corrected:
var answer = prompt('what do you want?');
if (answer === 'coke') {
console.log('you said coke!');
} else {
console.log('why didn\'t you say coke!?');
}
You could also use a switch as you get more cases:
var answer = prompt('what do you want?');
switch (answer) {
case 'coke':
console.log('you said coke!');
break;
default:
console.log('why didn\'t you say coke!?');
break;
}
Or an object, as most people prefer this to switch:
var answer = prompt('what do you want?');
var responses = {
coke: 'you said coke!',
defaultResponse: 'why didn\'t you say coke!?'
};
console.log(responses[answer] || responses.defaultResponse);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With