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

12.1k21 gold badges91 silver badges136 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,0788 gold badges60 silver badges88 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

5,09434 gold badges79 silver badges116 bronze badges

answered Aug 1, 2022 at 8:49

Coding.Cleo's user avatar

Когда встречается. Допустим, вы пишете цикл 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);

Short answer unexpected token else

Unexpected token ‘else’ is an error message that occurs when a JavaScript programming language compiler encounters the “else” statement in an unexpected context. This happens typically when there is a missing opening curly brace or syntax error on the preceding block of code.

The Step-by-Step Guide to Dealing with Unexpected Token Else Errors

As a programmer, it’s not uncommon to come across unexpected token else errors. These can be frustrating and time-consuming to debug, especially when you’re working on a large project with lots of nested conditionals.

However, fear not! With the right approach and some careful troubleshooting steps, you’ll get your code back up and running in no time. Here are some helpful tips for dealing with these pesky errors:

Step 1: Check Your Syntax
The first thing you should do is check your syntax. Unexpected token else errors typically occur when there is a problem with the way your code is written or structured. Make sure that all opening brackets have corresponding closing brackets, and that you’ve used proper indentation to clearly show how different parts of your code relate to one another.

Step 2: Double-Check Your Conditionals
Next, take a closer look at your if/else statements or switch/case blocks. Are they constructed correctly? Do you have any typos in them? It’s easy to misplace parentheses or forget an equal sign – simple mistakes like this can cause all sorts of issues. Carefully examine each line of code within these structures until you spot what may be causing the issue.

Step 3: Let Another Set Of Eyes Look At The Codebase
If step two does not offer any solutions then allowing someone else (a colleague) who has experience in programming language interaction could really help.

Step 4: Utilize Error Messages/Debugging Tools
Sometimes the root error message suggesting ‘unexpected token else’ doesn’t reflect where exactly the error comes from; thus using debugging tools such as break-points within IDE/debuggers could reveal other useful information regarding why things break unexpectedly

In Conclusion…
Dealing with unexpected token else errors may seem daunting but by following these straightforward approaches outlined above we’re confident that even novice programmers will manage just fine once everything stated above has been reviewed thoroughly.

Remember, coding is an ever-evolving process so always strive to learn from your experiences and take every opportunity to refine your skills. Happy Debugging!

Frequently Asked Questions about Unexpected Token Else in Programming

Unexpected token else is a common error that programmers encounter while working on various projects. It is mostly seen when using conditional statements like if-else, switch case or while loop.

Here are some frequently asked questions about unexpected token else in programming:

1.What does the phrase ‘unexpected token’ indicate?

The term ‘token’ refers to individual words or symbols within a code line which has specific meaning and purpose for that particular language. The occurrence of the term ‘unexpected token‘ indicates an instance of incorrect coding where a symbol expected in standard syntax is missing.

2.What triggers this problem?

Unexpected Token Else usually occurs while writing complex statements with multiple conditions whose structure might be ambiguous resulting in errors such as unclosed braces, parentheses not being balanced, wrong use of logical operators etc.

3.How can we fix it?

This error requires debugging by reviewing the entire statement as well as checking for other typos and potential syntax issues. Rectifying the actual cause may require referencing documentations or browsing online forums to get assistance from others who have faced similar challenges previously.

4.Can Unexpected Token Else affect program efficiency?

No, fixing this issue depends mostly upon your diligence towards proper programming etiquette so it does not jeopardize the functionality of any given project nor slow its performance down to any degree when resolved promptly carefully

5.How can we avoid this troublesome error altogether?

It’s important to follow best practices such as meticulous commenting followed by targeted testing plans . Learning languages thoroughly before propelling into larger projects also commonly helps avoid mistakes related strictly too basic misconceptions However most importantly remaining patient and persistent throughout development process can go long way ensuring unforeseeable errors don’t impede productivity unnecessarily unduly.

Top 5 Facts You Need to Know about Unexpected Token Else in Javascript

Javascript is a language that has taken over the web development world with its amazing features and functionalities. However, one of the most common errors faced by developers while coding in Javascript is the “Unexpected Token Else” error.

This error occurs when there is an improper use of conditionals, causing the interpreter to misconstrue the code. In this blog post, we will delve deeper into what causes Unexpected token else in JavaScript and provide top five facts you need to know about it.

1) Missing open or close curly braces
One of the most common reasons why this error occurs is due to incorrect syntax – specifically, missing opening or closing curly braces for conditional statements such as if-else blocks. This results in an unexpected token else being thrown by the parser since it cannot find where to evaluate your statement.

2) Not using semicolons properly
Javascript relies on semi-colons for proper termination of statements; failing which could lead to errors like “Unexpected Token Else”. If you don’t correctly terminate your previous statement with a semicolon before starting another conditional block,
It puts everything out of whack resulting in ambiguous flow control evaluation sequence that makes little sense leading potentially unreliable behavior down other line branches.

3) Incorrect usage within switch statements
Though correct grammar can prevent such typos from invalidating code logically concerned only with If/Else scenarios though situations arise where Switch cases may call similar unrecognized commands landing on cases were ‘unexpected arguments’ are seen without any clear rationale as these comparisons may occur further pushing alternate consequences downward strands execution order until explicitly defined elsewhere

4) Improper use inside For loops
Improperly placing your Else statement inside a loop can cause unpredictable outcomes because logical brackets might not always align as intended based upon distance between pertinent sections. Hence many times smaller details go unnoticed ultimately inviting bugs within larger programs thereby demanding tedious level detail-focused troubleshooting

5) A simple typo could be causing this problem!
The ‘Unexpected Token Else’ error can sometimes be caused by something as simple as a typing mistake, i.e., using “else” in lower-case letters or misspelling. This type of issue doesn’t necessarily stop the compiler from interpreting your program correctly; thus subtle issues may arise over an extended period rendering non-sensical results until noticed.

In conclusion,
The ‘Unexpected Token Else’ is a common programming error seen during Javascript coding that arises due to various reasons such as syntax errors, typos and other similar confusions causing compilers to break up execution. In most cases, it is correctable either by fixing the code structure or through implementing more detailed provisions prohibiting inadvertent inputs (for instance into method signatures). Developers should always keep their semantic language skills updated and frequently prioritize conducting rigorous debugging processes on all codes segments modified/created. By emphasizing these guidelines developers should easily intensify functional confidence behind their creations.

Debugging Techniques for Fixing Unwanted and Unexpected else Tokens

As a programmer, we all face the nightmare scenario of encountering unwanted and unexpected else tokens when debugging our code. It can be frustrating to spend hours trying to figure out why our program isn’t running as expected. Fortunately, there are some effective techniques that can help you fix this pesky problem.

Firstly, it’s important to understand what an else token is and when it should be used in your code. An else statement in a programming language acts as a conditional instruction that executes if the preceding if statement evaluates false and is not followed by another if or elseif statement.

Next, check for syntax errors as they often cause issues with matched brackets where you need explicit matches but rather get implicit matches.Don’t forget, syntax errors occur even in cases where there aren’t visible character mistakes so try reusing parts of existing known functioning codes while keeping track of each line edited.

Ensure also that the specific `if` for which your code wasn’t working had been appropriately encapsulated within curly braces (“{}”). Even If only one command were specified after ‘if,’ make sure curlies accompany such commands too; avoid putting multiple statements on one line unless using semicolons effectively turns them into one-liners’ Try indenting logically-arranged blocks underneath their paired curly brace “{” since doing otherwise could introduce accidental Elses’.Thus confirming proper closure would go miles towards eradicating unwanted Else statments

Another helpful technique involves employing print statements at strategic points throughout your script. By inserting deft printf outputs inside key structures during declarative block evaluations i.e before and after iteration loops,you might quickly latch onto certain areas inducing uninvited Else segments.Prettyprinting with deeply-nested sections goes even further clarifying wildly-inducing Else sources .

It’s generally advisable to use established integrated development environments (IDEs) like Pycharm/VS Code just in case any unknown configuration-related factors induced unwanted faults.It follows ,establishing workflows using such tools that support *incremental compilation* will save you heaps of time. Eliminating an Else matching loop input absence could be facilitated through these preprocessing functions to display ID(Identity) and other related phenomena especially allowing access to observables in real-time

Lastly, there’s no harm with seeking advice from veteran techies or browsing stack overflow for insight into how they overcame similar issues.Through understanding alorithmic design constructs the whys behind their successes ,one is better prepared for debugging hellholes.Arrive at a combination of both human assistance and AI-powered debuggers like PyCharm watch expressions would greatly shorten your pursuit towards solving unwanted Elses.

In conclusion,debugging unexpected tokens can be frustrating but by employing strategic techniques as highlighted above involving printer statements/Metaprogramming (JIT), syntax analysis/nested-block encapsulation avoidance & graceful smart IDE construction assurance/polymorphic identity aggregations;can go miles ensuring timely bugfixes .Happy programming!

Ways to Prevent the Common Syntax Error: Unexpected Token else

Syntax errors are one of the most frustrating types of errors that programmers face on a daily basis. These errors occur when the code is not written correctly, and can result in programs failing to run altogether or generating incorrect output. One common syntax error that many programmers encounter is the “Unexpected Token else”. This error can be particularly tricky to diagnose because it may not always be immediately clear what has caused it.

Thankfully, there are several ways that you can avoid this type of error entirely. The following tips will help you to prevent unexpected token ‘else’ from occurring in your code so that you can write more efficient, effective and bug-free programs!

1. Use an IDE:

An integrated development environment (IDE) is an essential tool for any programmer looking to write high-quality software efficiently. Most modern IDEs come with powerful debugging tools and features designed specifically to detect and help correct syntax errors such as unexpected tokens like ‘else’. With a good IDE at your disposal, you’ll have access to intelligent auto-correction services meaning fewer mistakes during coding! Embrace all the available key binds as they’ll save time while programming.

2. Know Your Codebase:

It’s important to familiarize yourself with your codebase before diving into the deep end writing complex statements such as conditional logic using asynchronous operations based on primitives; get well-acquainted with their properties so as o mitigate risk association experience along nested brackets being used appropriately- misused braces could culminate into logical incongruities inducing further mishaps.

3. Format Your Code Properly:

Very often than not inexperienced folk who fail sorting samples content or label miss interpreters presented them which eventually returns false values unknown at runtime producing far-fetched mismatched semantics marked by gibberish informality across spectrum- try giving specific names thereby adhering correct tags/headers within codespace ensuring easy reference against specified variables..

4. Keep An Eye On The Syntax Highlighting:

While editing your code in IDEs, always keep a watchful eye on the syntax highlighting. This will highlight any errors such as typos or incorrect symbols in real-time, allowing you to fix them before they become significant issues that culminate into unexpected token ‘else’.

5. Constantly Refactor Your Codebase:

Code refactoring is a crucial aspect of software development and should be done regularly. By refactoring your code, you can identify and remove any potential sources of error automatically introduced during developmental phase saving whole life cycle duration; it addresses other issues while eliminating redundancy/inefficiencies from the previous version with flexible maintaining an adaptive system.

In conclusion, preventing “Unexpected Token else” errors requires a combination of vigilance, knowledge about different programmatic structures along maintaining conventions during pre-processing phases suitable for all programming languages appropriate protocols technique adaptation level linked by best practices hardwired frameworks extending flexibility save time which subsequently ensure efficient rehability.. Embrace these tips to improve your understanding of programming concepts and write better-quality code that not only works efficiently but also enhances customer satisfaction!

Flawed coding practices can lead to disastrous outcomes when it comes to programming. A single mistake is enough to crash an entire application or cause unexpected behavior in your program. One such mistake that programmers often make is misplacing their “else” statements.

An else statement is used after an if condition has been flagged as false and specifies what should be executed next in case this first requirement does not occur. When placed correctly, else conditions can help ensure proper and stable program execution flow.

But imagine the scenario where you place the “else” statement incorrectly – disaster! The ‘if’ statement will execute its true condition branch, but then go ahead and execute another block under the mistaken idea that it was part of the initial semantic structure defining said boolean check. This inevitably leads to error messages and data corruption like unwanted input/output behaviors; leading to some really nasty bugs which are difficult to debug!

The consequences of a misplaced ‘else’ declaration for instance could mean failing user privilege checks issues becoming authentically non-existent; resulting in vulnerabilities ranging from session tampering by third parties with malicious intents over possibly deleting vital system logs unchecked-the list goes on ad infinitum…

In addition- reducing code blocks optimizes speed performance overall allowing for applications run faster through memory units every time they’re invoked without sacrificing integrity assurance at these core levels since there’s less complexity being compiled than before (as long as syntax errors don’t crop up!).

Therefore developers must pay close attention during their testing phase because just one line out-of-place can send everything into chaos mode! It also shows how vital emphasis upon syntactically correct code construction planning must be honed in till automated suggestions become instantaneously feasible– truly mind-boggling times indeed.

So programmers beware: always take care while coding, and make sure those ‘else’ statements are exactly where they need to be!

Table with useful data:

Error Message Description
Unexpected token else A syntax error that occurs when an “else” statement is used without an “if” statement before it.
Unexpected token ; A syntax error that occurs when a semicolon is used incorrectly, such as after a function declaration.
Unexpected token < A syntax error that occurs when an HTML tag is not properly closed or nested.
Unexpected token = A syntax error that occurs when the assignment operator is used incorrectly, such as in a conditional statement.

Information from an expert: As a programming expert, I have encountered the error message “unexpected token else” on numerous occasions. This message is typically displayed when there is a syntax error in the coding of an if-else statement. The most common cause of this error is forgetting to include curly braces around multiple statements within the if or else block. It can also occur if there are missing or misplaced parentheses, brackets, semicolons or commas. Debugging such errors requires careful attention to detail and close inspection of the code in question. My advice for any programmer facing this issue is to carefully review and edit their code until all syntax errors are fixed.

Historical fact:

The unexpected token “else” is a common error message encountered by programmers and has no significant historical relevance in the field of history.

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.

Skip to content

I am trying to make rock paper scissors in JS, everything is working but its showing error while using else if. My game gives you ten chances to play and the one who scores more points wins the game. Currently, I am trying to make this game play between computer and user 11 time. I tried using if statements for the conditions but I don’t know why the computer only played two times and then I tried using else if and then this error was coming. My code is below-

// rock paper scissor

const getRandom = (arr) => {
  return arr[Math.floor(Math.random() * arr.length)];
};

console.log("Welcome to rock,paper and scissors. you will play against the computer.You will have ten chances to prove your worth")

let chances = 0

const arr = ["stone", "paper", "scissor"]
let rand = (getRandom(arr));

while (chances <= 11) {
  let inp = prompt("Please enter the value")

  if (inp == 'stone' && rand == 'scissor')
    console.log("you won")
    chances += 1
  console.log(chances)
  // ``````````````````````````````````````````````````````
  else if (inp == 'stone' && rand == 'paper')
    console.log("you lost")
  chances += 1
  console.log(chances)
  // ``````````````````````````````````````````````````````
  else if (inp == 'stone' && rand == 'stone')
    console.log("its a tie!!")
  chances += 1
  console.log(chances)
  // ``````````````````````````````````````````````````````  paper
  else if (inp == 'paper' && rand == 'scissor')
    console.log("you lost")
  chances += 1
  console.log(chances)
  // ``````````````````````````````````````````````````````  
  else if (inp == 'paper' && rand == 'stone')
    console.log("you won")
  chances += 1
  // ``````````````````````````````````````````````````````  
  else if (inp == 'paper' && rand == 'paper')
    console.log("its a tie")
  chances += 1
  // ``````````````````````````````````````````````````````  scissor
  else if (inp == 'scissor' && rand == 'stone')
    console.log("you lost")
  chances += 1
  // ``````````````````````````````````````````````````````  
  else if (inp == 'scissor' && rand == 'paper')
    console.log("you won")
  chances += 1
  // ``````````````````````````````````````````````````````  
  elseif (inp == 'scissor' && rand == 'scissor')
    console.log("its a tie")
  chances += 1
}

The error is –

else if (inp == 'stone' && rand == 'paper')
SyntaxError: Unexpected token 'else'

>Solution :

If you want to execute more than one statement in an if, you need to create a block, using brackets ({ … }):

if (inp == 'stone' && rand == 'scissor') {
    console.log("you won")
    chances += 1
    console.log(chances)
  // ``````````````````````````````````````````````````````
}
else if (inp == 'stone' && rand == 'paper') {
    console.log("you lost")
    chances += 1
    console.log(chances)
}

More information here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/if…else

Понравилась статья? Поделить с друзьями:
  • Ue33 ошибка пионер
  • Unexpected token else after effects ошибка
  • Udisplay drv pc building simulator ошибка
  • U9n ошибка сигнализации starline a91
  • Unexpected store exception ошибка windows 10 как устранить