Uncaught syntaxerror invalid or unexpected token как исправить

Если вылезла ошибка «Uncaught SyntaxError: Unexpected token», скорее всего, вы пропустили скобку, кавычку, запятую или что-то подобное.

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

I am running an AJAX call in my MooTools script, this works fine in Firefox but in Chrome I am getting a Uncaught SyntaxError: Unexpected token : error, I cannot determine why. Commenting out code to determine where the bad code is yields nothing, I am thinking it may be a problem with the JSON being returned. Checking in the console I see the JSON returned is this:

{"votes":47,"totalvotes":90}

I don’t see any problems with it, why would this error occur?

vote.each(function(e){
  e.set('send', {
    onRequest : function(){
      spinner.show();
    },
    onComplete : function(){
      spinner.hide();
    },
    onSuccess : function(resp){
      var j = JSON.decode(resp);
      if (!j) return false;
      var restaurant = e.getParent('.restaurant');
      restaurant.getElements('.votes')[0].set('html', j.votes + " vote(s)");
      $$('#restaurants .restaurant').pop().set('html', "Total Votes: " + j.totalvotes);
      buildRestaurantGraphs();
    }
  });

  e.addEvent('submit', function(e){
    e.stop();
    this.send();
  });
});

asked Jun 29, 2010 at 18:37

trobrock's user avatar

trobrocktrobrock

46k11 gold badges38 silver badges45 bronze badges

6

Seeing red errors

Uncaught SyntaxError: Unexpected token <

in your Chrome developer’s console tab is an indication of HTML in the response body.

What you’re actually seeing is your browser’s reaction to the unexpected top line <!DOCTYPE html> from the server.

miken32's user avatar

miken32

41.1k16 gold badges106 silver badges149 bronze badges

answered Oct 28, 2014 at 17:56

andy magoon's user avatar

andy magoonandy magoon

2,8512 gold badges19 silver badges14 bronze badges

9

Just an FYI for people who might have the same problem — I just had to make my server send back the JSON as application/json and the default jQuery handler worked fine.

answered Aug 28, 2010 at 20:19

Edward Abrams's user avatar

Edward AbramsEdward Abrams

8851 gold badge6 silver badges3 bronze badges

5

This has just happened to me, and the reason was none of the reasons above. I was using the jQuery command getJSON and adding callback=? to use JSONP (as I needed to go cross-domain), and returning the JSON code {"foo":"bar"} and getting the error.

This is because I should have included the callback data, something like jQuery17209314005577471107_1335958194322({"foo":"bar"})

Here is the PHP code I used to achieve this, which degrades if JSON (without a callback) is used:

$ret['foo'] = "bar";
finish();

function finish() {
    header("content-type:application/json");
    if ($_GET['callback']) {
        print $_GET['callback']."(";
    }
    print json_encode($GLOBALS['ret']);
    if ($_GET['callback']) {
        print ")";
    }
    exit; 
}

Hopefully that will help someone in the future.

answered May 2, 2012 at 11:35

Grim...'s user avatar

Grim…Grim…

16.3k7 gold badges42 silver badges60 bronze badges

3

I have just solved the problem. There was something causing problems with a standard Request call, so this is the code I used instead:

vote.each(function(element){                
  element.addEvent('submit', function(e){
    e.stop();
    new Request.JSON({
      url : e.target.action, 
      onRequest : function(){
        spinner.show();
      },
      onComplete : function(){
        spinner.hide();
      },
      onSuccess : function(resp){
        var j = resp;
        if (!j) return false;
        var restaurant = element.getParent('.restaurant');
        restaurant.getElements('.votes')[0].set('html', j.votes + " vote(s)");
        $$('#restaurants .restaurant').pop().set('html', "Total Votes: " + j.totalvotes);
        buildRestaurantGraphs();
      }
    }).send(this);
  });
});

If anyone knows why the standard Request object was giving me problems I would love to know.

answered Jun 30, 2010 at 20:27

trobrock's user avatar

trobrocktrobrock

46k11 gold badges38 silver badges45 bronze badges

6

I thought I’d add my issue and resolution to the list.

I was getting: Uncaught SyntaxError: Unexpected token < and the error was pointing to this line in my ajax success statement:

var total = $.parseJSON(response);

I later found that in addition to the json results, there was HTML being sent with the response because I had an error in my PHP. When you get an error in PHP you can set it to warn you with huge orange tables and those tables were what was throwing off the JSON.

I found that out by just doing a console.log(response) in order to see what was actually being sent. If it’s an issue with the JSON data, just try to see if you can do a console.log or some other statement that will allow you to see what is sent and what is received.

answered Dec 19, 2013 at 2:50

Keven's user avatar

KevenKeven

3,92114 gold badges57 silver badges77 bronze badges

2

When you request your JSON file, server returns JavaScript Content-Type header (text/javascript) instead of JSON (application/json).

According to MooTools docs:

Responses with javascript content-type will be evaluated automatically.

In result MooTools tries to evaluate your JSON as JavaScript, and when you try to evaluate such JSON:

{"votes":47,"totalvotes":90}

as JavaScript, parser treats { and } as a block scope instead of object notation. It is the same as evaluating following «code»:

"votes":47,"totalvotes":90

As you can see, : is totally unexpected there.

The solution is to set correct Content-Type header for the JSON file. If you save it with .json extension, your server should do it by itself.

answered Dec 29, 2015 at 14:38

Michał Perłakowski's user avatar

It sounds like your response is being evaluated somehow. This gives the same error in Chrome:

var resp = '{"votes":47,"totalvotes":90}';
eval(resp);

This is due to the braces ‘{…}’ being interpreted by javascript as a code block and not an object literal as one might expect.

I would look at the JSON.decode() function and see if there is an eval in there.

Similar issue here:
Eval() = Unexpected token : error

Community's user avatar

answered Aug 13, 2015 at 19:39

Zectbumo's user avatar

ZectbumoZectbumo

3,6501 gold badge30 silver badges24 bronze badges

This happened to me today as well. I was using EF and returning an Entity in response to an AJAX call. The virtual properties on my entity was causing a cyclical dependency error that was not being detected on the server. By adding the [ScriptIgnore] attribute on the virtual properties, the problem was fixed.

Instead of using the ScriptIgnore attribute, it would probably be better to just return a DTO.

answered Mar 24, 2016 at 22:31

Daryl's user avatar

DarylDaryl

6101 gold badge7 silver badges16 bronze badges

If nothing makes sense, this error can also be caused by PHP Error that is embedded inside html/javascript, such as the one below

<br />
<b>Deprecated</b>:  mysql_connect(): The mysql extension is deprecated and will be removed in the future: use mysqli or PDO instead in <b>C:Projectsrwpdemoensuperge.php</b> on line <b>54</b><br />
var zNodes =[{ id:1, pId:0, name:"ACE", url: "/ace1.php", target:"_self", open:true}

Not the <br /> etc in the code that are inserted into html by PHP is causing the error. To fix this kind of error (suppress warning), used this code in the start

error_reporting(E_ERROR | E_PARSE);

To view, right click on page, «view source» and then examine complete html to spot this error.

answered Nov 9, 2018 at 19:45

Hammad Khan's user avatar

Hammad KhanHammad Khan

16k16 gold badges111 silver badges134 bronze badges

«Uncaught SyntaxError: Unexpected token» error appearance when your data return wrong json format, in some case, you don’t know you got wrong json format.
please check it with alert(); function

onSuccess : function(resp){  
   alert(resp);  
}

your message received should be: {«firstName»:»John», «lastName»:»Doe»}
and then you can use code below

onSuccess : function(resp){  
   var j = JSON.decode(resp); // but in my case i'm using: JSON.parse(resp); 
}

with out error «Uncaught SyntaxError: Unexpected token«
but if you get wrong json format
ex:

…{«firstName»:»John», «lastName»:»Doe»}

or

Undefined variable: errCapt in .... on line<b>65</b><br/>{"firstName":"John", "lastName":"Doe"}

so that you got wrong json format, please fix it before you JSON.decode or JSON.parse

answered Mar 17, 2015 at 10:11

Rain's user avatar

RainRain

6016 silver badges10 bronze badges

1

This happened to because I have a rule setup in my express server to route any 404 back to /# plus whatever the original request was. Allowing the angular router/js to handle the request. If there’s no js route to handle that path, a request to /#/whatever is made to the server, which is just a request for /, the entire webpage.

So for example if I wanted to make a request for /correct/somejsfile.js but I miss typed it to /wrong/somejsfile.js the request is made to the server. That location/file does not exist, so the server responds with a 302 location: /#/wrong/somejsfile.js. The browser happily follows the redirect and the entire webpage is returned. The browser parses the page as js and you get

Uncaught SyntaxError: Unexpected token <

So to help find the offending path/request look for 302 requests.

Hope that helps someone.

answered Jan 26, 2018 at 21:14

Jerinaw's user avatar

JerinawJerinaw

5,1107 gold badges39 silver badges52 bronze badges

I had the same problem and it turned out that the Json returned from the server
wasn’t valid Json-P. If you don’t use the call as a crossdomain call use regular Json.

Community's user avatar

answered Nov 13, 2013 at 8:31

jakob's user avatar

jakobjakob

5,9817 gold badges62 silver badges103 bronze badges

1

My mistake was forgetting single/double quotation around url in javascript:

so wrong code was:

window.location = https://google.com;

and correct code:

window.location = "https://google.com";

answered Apr 11, 2020 at 8:03

Saeed Arianmanesh's user avatar

In my case putting / at the beginning of the src of scripts or href of stylesheets solved the issue.

answered Jul 1, 2021 at 13:02

Vahid Kiani's user avatar

1

I got this error because I was missing the type attribute in script tag.

Initially I was using but when I added the type attribute inside the script tag then my issue is resolved

answered Jul 28, 2022 at 15:37

Hemant 's user avatar

Hemant Hemant

855 bronze badges

I got a «SyntaxError: Unexpected token I» when I used jQuery.getJSON() to try to de-serialize a floating point value of Infinity, encoded as INF, which is illegal in JSON.

answered Jul 18, 2013 at 19:52

Mark Cidade's user avatar

Mark CidadeMark Cidade

97.8k31 gold badges222 silver badges236 bronze badges

1

In my case i ran into the same error, while running spring mvc application due to wrong mapping in my mvc controller

@RequestMapping(name="/private/updatestatus")

i changed the above mapping to

 @RequestMapping("/private/updatestatus")

or

 @RequestMapping(value="/private/updatestatus",method = RequestMethod.GET)

answered Sep 26, 2015 at 3:58

Shravan Ramamurthy's user avatar

For me the light bulb went on when I viewed the source to the page inside the Chrome browser. I had an extra bracket in an if statement. You’ll immediately see the red circle with a cross in it on the failing line. It’s a rather unhelpful error message, because the the Uncaught Syntax Error: Unexpected token makes no reference to a line number when it first appears in the console of Chrome.

answered Jun 21, 2017 at 13:47

JGFMK's user avatar

JGFMKJGFMK

8,1354 gold badges53 silver badges92 bronze badges

I did Wrong in this

   `var  fs = require('fs');
    var fs.writeFileSync(file, configJSON);`

Already I intialized the fs variable.But again i put var in the second line.This one also gives that kind of error…

answered Jul 21, 2017 at 6:13

Janen R's user avatar

Janen RJanen R

72910 silver badges20 bronze badges

For those experiencing this in AngularJs 1.4.6 or similar, my problem was with angular not finding my template because the file at the templateUrl (path) I provided couldn’t be found. I just had to provide a reachable path and the problem went away.

answered Feb 2, 2018 at 5:08

lwdthe1's user avatar

lwdthe1lwdthe1

7771 gold badge12 silver badges12 bronze badges

1

In my case it was a mistaken url (not existing), so maybe your ‘send’ in second line should be other…

answered Dec 20, 2018 at 18:01

Michal - wereda-net's user avatar

This error might also mean a missing colon or : in your code.

answered Oct 6, 2020 at 10:15

Cons Bulaquena's user avatar

Cons BulaquenaCons Bulaquena

2,0432 gold badges26 silver badges24 bronze badges

Facing JS issues repetitively I am working on a Ckeditor apply on my xblock package. please suggest to me if anyone helping me out. Using OpenEdx, Javascript, xblock

xblock.js:158 SyntaxError: Unexpected token '=>'
at eval (<anonymous>)
at Function.globalEval (jquery.js:343)
at domManip (jquery.js:5291)
at jQuery.fn.init.append (jquery.js:5431)
at child.loadResource (xblock.js:236)
at applyResource (xblock.js:199)
at Object.<anonymous> (xblock.js:202)
at fire (jquery.js:3187)
at Object.add [as done] (jquery.js:3246)
at applyResource (xblock.js:201) "SyntaxError: Unexpected token '=>'n    at eval (<anonymous>)n    at Function.globalEval (http://localhost:18010/static/studio/common/js/vendor/jquery.js:343:5)n    at domManip (http://localhost:18010/static/studio/common/js/vendor/jquery.js:5291:15)n    at jQuery.fn.init.append (http://localhost:18010/static/studio/common/js/vendor/jquery.js:5431:10)n    at child.loadResource (http://localhost:18010/static/studio/bundles/commons.js:5091:27)n    at applyResource (http://localhost:18010/static/studio/bundles/commons.js:5054:36)n    at Object.<anonymous> (http://localhost:18010/static/studio/bundles/commons.js:5057:25)n    at fire (http://localhost:18010/static/studio/common/js/vendor/jquery.js:3187:31)n    at Object.add [as done] (http://localhost:18010/static/studio/common/js/vendor/jquery.js:3246:7)n    at applyResource (http://localhost:18010/static/studio/bundles/commons.js:5056:29)"

answered Nov 13, 2021 at 18:47

Neeraj Kumar's user avatar

Late to the party but my solution was to specify the dataType as json. Alternatively make sure you do not set jsonp: true.

answered May 9, 2022 at 9:17

Karim Tingdis's user avatar

Try this to ignore this issue:

Cypress.on('uncaught:exception', (err, runnable) => {
        return false;
    });

answered Sep 9, 2022 at 11:17

Sudheer Singh's user avatar

Uncaught SyntaxError: Unexpected token }

Chrome gaved me the error for this sample code:

<div class="file-square" onclick="window.location = " ?dir=zzz">
    <div class="square-icon"></div>
    <div class="square-text">zzz</div>
</div>

and solved it fixing the onclick to be like

... onclick="window.location = '?dir=zzz'" ...

But the error has nothing to do with the problem..

answered Sep 24, 2013 at 9:21

ungalcrys's user avatar

ungalcrysungalcrys

5,0962 gold badges38 silver badges23 bronze badges

1

Doctype html unexpected token: The “Uncaught SyntaxError: Unexpected token” error can occur for a variety of reasons, including:

  • Using a <script /> tag that leads to an HTML file rather than a JS file.
  • Receiving an HTML response from a server where JSON is expected,
  • Having a <script /> tag that leads to the wrong path.
  • When your code is missing or contains extra brackets, parenthesis, or commas.
  • When you forgot to close the <script />tag.

Let us see some of the cases where the “Uncaught SyntaxError: Unexpected token” error Occurs

Cases where the “Uncaught SyntaxError: Unexpected token” error Occurs

Example1

Unexpected token js: Below is an example of an error: our script tag points to a html file rather than a JS file.

index.html:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
  </head>

  <body>
    <!-- Here script tag is pointing to an html file instead of JS file 
    Hence Uncaught SyntaxError: Unexpected token '<' occurs-->
    <script src="index.html"></script>
  </body>
</html>

NOTE:

Check that any script tag you use lead to a valid path, and try to rename all your files
using just lowercase characters. 
If the file name contains uppercase letters or special characters, the error may occur.

Example2

Unexpected token doctype: The other common cause of the “Uncaught SyntaxError: Unexpected token” is when we forget to close a script tag.

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />

    <!-- Here we forgot to close the script tag, hence 
    Uncaught SyntaxError: Unexpected token '<' occurs -->
    <script
      console.log("Uncaught SyntaxError: Unexpected token '<'");
    </script>
  </head>

  <body></body>
</html>
  • When attempting to parse JSON data, the error is also generated if you make an http request to a server and receive an HTML response.
  • To solve this we can use console.log. The response you receive from your server and ensure it is a proper JSON string free of HTML tags.
  • Alternatively, you can open your browser’s developer tools, navigate to the Network tab, and inspect the response.

Example3: index.js (Giving another extra curly brace)

// Create a function say multiply whict accepts two numbers
// as arguments and returns the multiplication result
function multiply(x, y) {
  // Multiply the above passed two numbers and return the result
  return x * y;
}}

Output:

}}
^

SyntaxError: Unexpected token }
at Module._compile (internal/modules/cjs/loader.js:723:23)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:789:10)
at Module.load (internal/modules/cjs/loader.js:653:32)
at tryModuleLoad (internal/modules/cjs/loader.js:593:12)
at Function.Module._load (internal/modules/cjs/loader.js:585:3)
at Function.Module.runMain (internal/modules/cjs/loader.js:831:12)
at startup (internal/bootstrap/node.js:283:19)
at bootstrapNodeJSCore (internal/bootstrap/node.js:623:3)

Explanation:

Here we gave another extra curly brace, hence SyntaxError: Unexpected token } occured

These syntax errors are difficult to spot, but an useful tip is:

  • If you receive the “Uncaught SyntaxError: Unexpected token ‘<‘” (ovserve the ‘<‘) error, you are most likely attempting to read HTML code that begins with ‘<‘.
  • If your error message comprises a curly brace, parenthesis, comma, colon, etc., you most certainly have a SyntaxError, which occurs when your code has an additional or missing character.

Example4: index.js (Giving colons two times(::) instead of once(:))

// Create an object and store it in a variable
const obj = {
  // Here we gave colons two times(::) instead of once(:) to separate the key-value pairs
  // so,the SyntaxError: Unexpected token : occurs
  Website:: "Btechgeeks",
}

Output:

Website:: "Btechgeeks",
^

SyntaxError: Unexpected token :
at Module._compile (internal/modules/cjs/loader.js:723:23)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:789:10)
at Module.load (internal/modules/cjs/loader.js:653:32)
at tryModuleLoad (internal/modules/cjs/loader.js:593:12)
at Function.Module._load (internal/modules/cjs/loader.js:585:3)
at Function.Module.runMain (internal/modules/cjs/loader.js:831:12)
at startup (internal/bootstrap/node.js:283:19)
at bootstrapNodeJSCore (internal/bootstrap/node.js:623:3)

Explanation:

Here we gave colons two times(::) instead of once(:) to separate the key-value pairs 
so,the SyntaxError: Unexpected token : occurs

Example5: index.js (Giving an extra comma)

// Create an object and store it in a variable
const obj = {
  // Here we gave an extra comma(,) 
  // Hence the SyntaxError: Unexpected token occurs
  Website: "Btechgeeks",,
}

Output:

Website: "Btechgeeks",,
^

SyntaxError: Unexpected token ,
at Module._compile (internal/modules/cjs/loader.js:723:23)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:789:10)
at Module.load (internal/modules/cjs/loader.js:653:32)
at tryModuleLoad (internal/modules/cjs/loader.js:593:12)
at Function.Module._load (internal/modules/cjs/loader.js:585:3)
at Function.Module.runMain (internal/modules/cjs/loader.js:831:12)
at startup (internal/bootstrap/node.js:283:19)
at bootstrapNodeJSCore (internal/bootstrap/node.js:623:3)

Fixing the “Uncaught SyntaxError: Unexpected token” Error

To resolve the “Uncaught SyntaxError: Unexpected token” error, make the following changes:

  • We should not have a <script/> tag that points to an HTML file, instead of a JS file.
  • Instead of requesting an HTML file from a server, you are requesting JSON.
  • There is no <script/> tag pointing to an incorrect path.
  • There must be no missing or excessive brackets, parenthesis, or commas.
  • Do not forget to close a <script tag.

This is a common error in JavaScript, and it is hard to understand at first why it happens. But if you bear with me and remember that Bugs are a good thing you will be on your way in no time.

TL;DR

The JavaScript file you are linking to is returning 404 page. In other words, the browser is expecting JavaScript but it is returning HTML results.

Here is a simple example that may cause this error.

// including jquery.js
// this script is myapp.js

// Get the json data instead of making a request
$(".mybtn").on("click",function(e){
    // Stop the default behaviour.
    e.preventDefault();
    //
    var jsonUrl = this.href + "&json=1";

    $.ajax({
        url: jsonUrl,
        type: "json",
        method: "get",

        success: function(data){
            // do something with the data
            alert(data);
        }
    });

});

In the example above, when the user clicks on a link an ajax request is triggered to return json data. If the json data is returned correctly, everyone is happy and move on. But if it doesn’t, well we have to fix it. In situations like this, it’s often common to see the error:

Uncaught SyntaxError: Unexpected token <

Don’t run to stackoverflow right away. What the interpreter is telling us is that it found a character it was not expecting. Here the interpreter was expecting json, but it received < or HTML. If you check the response on your network developer tab, you will see that the response is HTML.

Another way you can get this error is if you add a script tag and have the src return HTML:

<script src="index.html"></script>

All it means is that the interpreter is expecting JavaScript or JSON and you are feeding it HTML/XML. If you don’t think you are returning HTML, check if you are not getting a 404.

<!DOCTYPE html>
<html>
...

How do I fix it?

Check the src path to your JavaScript to make sure it is correct. If you are making an Ajax request also check the path. Either the path is incorrect, or the file doesn’t exist.


Did you like this article? You can subscribe to read more awesome ones. RSS

Sign up for the Newsletter.

Follow me on
Twitter

Improve Article

Save Article

  • Read
  • Discuss
  • Improve Article

    Save Article

    Like other programming languages, JavaScript has define some proper programming rules. Not follow them throws an error.An unexpected token occurs if JavaScript code has a missing or extra character { like, ) + – var if-else var etc}. Unexpected token is similar to syntax error but more specific.Semicolon(;) in JavaScript plays a vital role while writing a programme.
    Usage: To understand this we should know JavaScript also has a particular syntax like in JavaScript are concluded by a semi-colon(;) and there are many rules like all spaces/tabs/newlines are considered whitespace. JavaScript code are parsed from left to right, it is a process in which the parser converts the statements and whitespace into unique elements.
     

    • Tokens: All the operator (+, -, if, else…) are reserved by the JavaScript engine.So, it cannot be used incorrectly .It cannot be used as part of variable names.
    • Line terminators: A JavaScript code should end with semi-colon(;).
    • Control characters: To control code, it is important to maintain braces({ }) in a code. It is also important to defines the scope of the code.
    • Comments: A line of code written after // is a comment. JavaScript ignores this line.
    • Whitespace: It is a tab/space in code.Changing it does not change the functionality of the code.

    Therefore JavaScript code is very sensitive to any typo error. These examples given below explain the ways that unexpected token can occur.
    Example 1: It was either expecting a parameter in myFunc(mycar, ) or not, .So it was enable to execute this code. 
     

    javascript

    <script>

    function multiple(number1, number2) {

        function myFunc(theObject) {

            theObject.make = 'Toyota';

        }

        var mycar = {

            make: 'BMW',

            model: 'Q8-7',

            year: 2005

        };

        var x, y;

        x = mycar.make;

        myFunc(mycar, );

        y = mycar.make;

    </script>

    Output: 
     

    Unexpected end of input

    Example 2: An unexpected token ‘, ‘occurs after i=0 which javascript cannot recognize.We can remove error here by removing extra. 
     

    javascript

    <script>

    for(i=0, ;i<10;i++)

    {

      document.writeln(i);

    }

    </script>

    Output: 
     

    expected expression, got ', '

    Example 3: An unexpected token ‘)’ occur after i++ which JavaScript cannot recognize.We can remove error here by removing extra ). 
     

    javascript

    <script>

    for(i=0;i<10;i++))

    {

      console.log(i);

    }

    </script>

    Output 
     

    expected expression, got ')'

    Example 4: At end of if’s body JavaScript was expecting braces “}” but instead it got an unexpected token else.If we put } at the end of the body of if. 
     

    javascript

    <script>

    var n = 10;

    if (n == 10) {

        console.log("TRUE");

        else {

            console.log("FALSE");

        }

    </script>

    Output 
     

    expected expression, got keyword 'else'

    Similarly, unnecessary use of any token will throw this type of error. We can remove this error by binding by following the programming rules of JavaScript.
     

    Понравилась статья? Поделить с друзьями:
  • Uncaught referenceerror require is not defined как исправить
  • Uncaught phpmailerexception smtp error data not accepted
  • Uncaught pdoexception could not find driver как исправить
  • Uncaught in promise error request failed with status code 500
  • Uncaught in promise error cannot find module