Unexpected token else javascript ошибка

I am learning Javascript via Codecademy and no have been stumped on this little piece here.

I have supposed to write an if else statement.

It shows me here in the following that there is a Syntac Error with a missing identifier:

var userAnswer = prompt("Are you feeling lucky, punk?");

if (userAnswer === "yes");
{

    console.log("Batman hits you very hard. It's Batman and you're you! Of course Batman wins!");
}

 else {

    console.log("You did not say yes to feeling lucky. Good choice! You are a winner in the game of not getting beaten up by Batman.");
}

What is wrong with that…. There is no error in this example here:

if (age < 18)

{

    console.log("We take no actions or responsibility. Play at your own risk!");
}

else

{

    console.log("Enjoy the game");
}

tshepang's user avatar

tshepang

12k21 gold badges91 silver badges135 bronze badges

asked Feb 1, 2014 at 16:18

user3260811's user avatar

1

if (userAnswer === "yes");

Remove the semicolon.

answered Feb 1, 2014 at 16:20

Niet the Dark Absol's user avatar

2

There’s a semi-colon after the first conditional check. Also, you should always put the opening bracket of the conditional branch on the same line as the brackets

answered Feb 1, 2014 at 16:20

danwellman's user avatar

danwellmandanwellman

9,0398 gold badges59 silver badges87 bronze badges

var age;
age = prompt('How old are you?');
if (age < 18)

{

alert("We take no actions or responsibility. Play at your own risk!");
}

else if(age > 18)

{

alert("Enjoy the game");
}

answered May 18, 2015 at 19:46

George's user avatar

1

remove the semicolon after

if (userAnswer === «yes»);

if you put the semicolon there, you are telling the script to stop there and not to render the next conditional statement that is «else»[SyntaxError: Unexpected token else]

1

vimuth's user avatar

vimuth

4,91330 gold badges78 silver badges115 bronze badges

answered Aug 1, 2022 at 8:49

Coding.Cleo's user avatar

I have this code for a rock, paper, scissors game that is basically homework. I have double-checked and it seems to be fine, however, when I run it it says:

SyntaxError: Unexpected token else, 

any help will be very appreciated :) Please note that I am a newbie, so if the question is dumb, please be nice and help <3

I just edited the code a bit, since I had many «Overlook» mistakes. I also wanted to clarify that I need all the code located after the function statement to be inside the function, that is why I don’t close the first { right away.
PD: Now I get: SyntaxError: Unexpected token =

var userChoice = prompt("Do you choose rock, paper or scissors?");
var computerChoice = Math.random();


if (computerChoice < 0.34) {
    computerChoice = "rock";
} else if(computerChoice <= 0.67) {
    computerChoice = "paper";
} else {
computerChoice = "scissors";
}

console.log("Computer: " + computerChoice);

var compare = function(choice1, choice2) {
    if (choice1 === choice2)
        return "The result is a tie!";
    else if (choice1 === "rock") {
        if (choice2 === "scissors") {
            return "rock wins";
      } else if (choice1 ==== "paper") {
            if (choice2 === "rock") {
                return "paper wins";
            else if (choice2 === "scissors") {
                return "scissors wins"; }

            else {
                return "Paper wins"; }    
            }
        }
}

compare(userChoice, computerChoice)

Доброго дня всем!
Есть список ссылок

<div class='links'>
   <a href='#'>link 1</a>
   <a href='#'>link 2</a>
   <a href='#'>link 3</a>
</div>

При нажатии на ссылку необходимо добавить ей фон, как выбранному элементу.
Средствами JS добавил class='selected' к тегу <a> при клике.

let active = document.getElementsByTagName("a") [0];
active.onclick = function() {
    if (active.classList.remove('selected'));
    	this.classList.add('selected');
	else
		active.classList.remove('selected');
}

Но если добавить else получаю ошибку.
Подскажите, что не так с кодом?

Когда встречается. Допустим, вы пишете цикл for на JavaScript и вспоминаете, что там нужна переменная цикла, условие и шаг цикла:

for var i = 1; i < 10; i++ {
<span style="font-weight: 400;">  // какой-то код</span>
<span style="font-weight: 400;">}</span>

После запуска в браузере цикл падает с ошибкой:

❌ Uncaught SyntaxError: Unexpected token ‘var’

Что значит. Unexpected token означает, что интерпретатор вашего языка встретил в коде что-то неожиданное. В нашем случае это интерпретатор JavaScript, который не ожидал увидеть в этом месте слово var, поэтому остановил работу.

Причина — скорее всего, вы пропустили что-то из синтаксиса: скобку, кавычку, точку с запятой, запятую, что-то подобное. Может быть, у вас была опечатка в служебном слове и язык его не распознал.

Что делать с ошибкой Uncaught SyntaxError: Unexpected token

Когда интерпретатор не может обработать скрипт и выдаёт ошибку, он обязательно показывает номер строки, где эта ошибка произошла (в нашем случае — в первой же строке):

Интерпретатор обязательно показывает номер строки, где произошла ошибка Uncaught SyntaxError: Unexpected token

Если мы нажмём на надпись VM21412:1, то браузер нам сразу покажет строку с ошибкой и подчеркнёт непонятное для себя место:

Строка с ошибкой Uncaught SyntaxError: Unexpected token

По этому фрагменту сразу видно, что браузеру не нравится слово var. Что делать теперь:

  • Проверьте, так ли пишется эта конструкция на вашем языке. В случае JavaScript тут не хватает скобок. Должно быть for (var i=1; i<10; i++) {}
  • Посмотрите на предыдущие команды. Если там не закрыта скобка или кавычка, интерпретатор может ругаться на код немного позднее.

Попробуйте сами

Каждый из этих фрагментов кода даст ошибку Uncaught SyntaxError: Unexpected token. Попробуйте это исправить.

if (a==b) then  {}
function nearby(number, today, oneday, threeday) {
  if (user_today == today + 1 || user_today == today - 1)
    (user_oneday == oneday + 1 || user_oneday == oneday - 1)
      && (user_threeday == threeday + 1 || user_threeday == threeday - 1)
  return true
  
  else
     return false
}
var a = prompt('Зимой и летом одним цветом');
if (a == 'ель'); {
  alert("верно");
} else {
  alert("неверно");
}
alert(end);

@Hakerh400 @ematt321 I don’t know what [refack: redacted], but this is the pattern you want to use:

var multiTax = function (income) {
  if (income <= 500000) {
    income = income * 0.35;
    return income;
  }
 // ... 
  if (income < 30000) {
    income = income * 0.10;
    return income;
  }
  else if (income >= 38701) {
    income = income * 0.22;
    return income;
  }
  else {
    income = income * 0.24;
    return income;
  }
};

console.log(multiTax(500001));

this can be abbreviated to:

var multiTax = function (income) {
  if (income <= 500000) {
   return income = income * 0.35;
  }
 // ... 
  if (income <  30000) {
    return income = income * 0.10;
  }
  else if (income >= 38701) {
    return  income = income * 0.22;
  }
  else {
    return income = income * 0.24;
  }
};

console.log(multiTax(500001));

which can be further abbreviated to:

var multiTax = function (income) {
  if (income <= 500000) {
   return income * 0.35;
  }
 // ... 
  if (income < 30000 ) {
    return income * 0.10;
  }
  else if (income >= 38701) {
    return income * 0.22;
  }
  else {
    return income * 0.24;
  }
};

console.log(multiTax(500001));

please pay attention.

Понравилась статья? Поделить с друзьями:
  • Unexpected termination ошибка
  • Unexpected store exception ошибка что это
  • Unexpected store exception windows 10 ошибка что означает
  • Unexpected store exception windows 10 ошибка синий экран
  • Unexpected store exception windows 10 ошибка как исправить