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,0498 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,93330 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);

Have a JavaScript Unexpected Token Error? Check Your Syntax

Jul 15, 2022 3:00:00 PM |
Have a JavaScript Unexpected Token Error? Check Your Syntax

A deep look at the Unexpected Token Error in JavaScript, including a short examination of JavaScript’s syntax best practices.

Today, we are discussing the Unexpected Token Error within our JavaScript Error Handling series. This JavaScript error is a subset of the SyntaxError. That means it only appears when attempting to execute code with an extra (or missing) character in the syntax.

Throughout this article, we’ll explore the Unexpected Token error, why it happens, and how to fix it.

The Technical Rundown

  • All JavaScript error objects descend from the Error object or an inherited object therein.
  • The SyntaxError object is inherited from the Error object.
  • The Unexpected Token error is a specific type of SyntaxError object.

Why Does an Unexpected Token Occur? 

JavaScript is particular about the way its syntax is written. While we don’t have time to cover everything that JavaScript expects (you can find that in the official documentation), it’s essential to understand the basic premise of how JavaScript parsers work.

Statements written in JavaScript code are instructions that are concluded with a semicolon (;), and any spaces/tabs/newlines are considered whitespace. JavaScript parses code from left to right, converting statements and whitespace into unique elements.

  • 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. 
  • Control characters: A subset of tokens that are used to direct the “flow” of the code into code blocks. These are used to maintain scope, with braces ({ … }) and the like.
  • Line terminators: As the name implies, a new line termination character.
  • Comments: Comments are indicated using 2 forward-slash characters (//). The JavaScript engine will not parse comments. 
  • Whitespace: Any space or tab characters that do not appear within a string definition. Effectively, if it can be removed without changing the functionality of the code, it is whitespace.

When JavaScript parses code, it converts everything into these characters. Once that’s done, the engine attempts to execute our statements in order. In situations where the syntax is wrong, we might encounter an Unexpected Token error. This means the parser thinks there should be another element in a particular place instead of the token the parser found.

How to Fix an Unexpected Token

The best way to learn how to fix an Unexpected Token error is to go through a couple of examples.

Your Punctuation is Incorrect

Below, we have a simple call to the Math.max() method. This method accepts a list of numeric arguments and returns the largest number from that list. 

Keen eyes will notice that we’ve accidentally included an additional comma (,) after our second argument (2,), which will be trouble for our parser:

// 1
var printError = function(error, explicit) {
console.log(`[${explicit ? 'EXPLICIT' : 'INEXPLICIT'}] ${error.name}: ${error.message}`);
}

try {
// Extra comma in Math.max
var value = Math.max(1, 2,);
console.log(value);
} catch (e) {
if (e instanceof SyntaxError) {
printError(e, true);
} else {
printError(e, false);
}
}

As expected, JavaScript wasn’t sure how to properly parse it. That’s why we received an Unexpected Token as a result:

// CHROME
Uncaught SyntaxError: Unexpected token )

// FIREFOX
SyntaxError: expected expression, got ')'

The problem could be one of two things:

  • We wanted to list three arguments but forgot one: Math.max(1, 2, 3).
  • We only wanted to list two arguments but included an additional comma: Math.max(1, 2).

JavaScript expected a third argument between that final comma and the closing parenthesis because of the extra comma in our method call. The lack of that third argument is what caused the error.

As mentioned earlier, there are many different types of Unexpected Token errors. Instead of covering all the possibilities, we’ll just look at one more common example.

You Have a Typo

The JavaScript’s parser expects tokens and symbols in a particular order, with relevant values or variables in between. Often, an Unexpected Token is due to an accidental typo. For the most part, you can avoid this by using a code editor that provides some form of auto-completion. 

Code editors are beneficial when forming basic logical blocks or writing out method argument lists because the editor will often automatically provide the necessary syntax.

But, there’s a downside to relying too heavily on the auto-complete feature. If it auto-completes something and you change it, it’s up to you to go back and fix it. 

For example, my code editor tried to fix the following snippet for me. So, I had to manually remove a brace (}) to get the desired result. Unfortunately, I forgot to go back and replace the missing brace. Because of this, an Unexpected Token error appeared in this simple if-else block:

var printError = function(error, explicit) {
console.log(`[${explicit ? 'EXPLICIT' : 'INEXPLICIT'}] ${error.name}: ${error.message}`);
}

try {
var name = «Bob»;
if (name === «Bob») {
console.log(`Whew, it’s just ${name}`);
else {
console.log(«Imposter!»);
}
} catch (e) {
if (e instanceof SyntaxError) {
printError(e, true);
} else {
printError(e, false);
}
}

When JavaScript parses this, it expects that brace character, but instead, it gets the else:

// CHROME
Uncaught SyntaxError: Unexpected token else

// FIREFOX
SyntaxError: expected expression, got keyword 'else'

Some keen observers may have noticed that even though we’re using the standard trappings of error capturing via a try-catch block to grab an instance of our SyntaxError, this code is never executed. The parser finds our SyntaxError and reports on it before it evaluates our catch block. You can catch Unexpected Token errors, but doing so typically requires the execution of the two sections (problematic code versus try-catch block) to take place in separate locations.

And, so, here comes our pitch.

Using Airbrake to Find JavaScript Errors

How long did it take you to find that one line of code causing the Unexpected Token error? With Airbrake Error & Performance Monitoring, you won’t have to sift through thousands of lines of code to find that one error that’s causing your application to fail. Instead, Airbrake will tell you EXACTLY where that error is, right down to the line of broken code. See for yourself with a free Airbrake dev account.

Note: We published this post in March 2017 and recently updated it in July 2022.

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