Prompt JavaScript If Else Unexpected Token else

强颜欢笑 提交于 2019-12-05 04:20:50

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

Actually DO NOT do

 if (ans == "whatever") {
    console.log ("whatever");
} else {
    console.log ("whatever.");
}

DO

 if (ans == "whatever") {
    confirm ("whatever");
} else {
    confirm ("whatever.");
}
jeromygoodnight

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!