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!
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);
The if does not need a semicolon at the end. Instead do:
if ("coke") {
console.log ("no coke, pepsi.");
} else {
console.log ("pepsi only.");
}
Remove the trailing semicolons:
prompt("what do you want?");
if ("coke") {
console.log ("no coke, pepsi.");
} else {
console.log ("pepsi only.");
}
var name = prompt("what do you want?");
if (name == "coke")
{
console.log ("no coke, pepsi.")
}
else
{
console.log ("pepsi only.")
}
Like above
You have a semi-colon after the close brace. Try:
var ans = prompt("what do you want?");
if (ans == "coke") {
console.log ("no coke, pepsi.");
} else {
console.log ("pepsi only.");
}
Actually DO NOT do
if (ans == "whatever") {
console.log ("whatever");
} else {
console.log ("whatever.");
}
DO
if (ans == "whatever") {
confirm ("whatever");
} else {
confirm ("whatever.");
}
A variable
needs to be identified. Also the bracketing and the semi colons between the "if" "else"
statements are problematic. I am not sure about the console log
, but if you want a popup alert try this:
var brand = prompt ('what do you want?');
if (brand="coke") {
alert ("no coke, pepsi.")
}else {
alert ("pepsi only.")
};
DICLAIMER: I am novice at best, jut happened to debug a similar issue. Hope it helps.
来源:https://stackoverflow.com/questions/12963350/prompt-javascript-if-else-unexpected-token-else