JavaScript

Uncaught SyntaxError: Unexpected token <

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.


Comments(21)

jardenilson da silva :

boa tarde estou com um script e quando executo aparece o erro:Uncaught SyntaxError: token inesperado tem como solucionar? pois preciso muito deste scripr

Ibrahim :

Hi @Jardenilson

The problem is that URL you are accessing is not a script. It is returning HTML. Most probably a page that is not found 404. So try to fix the url and it should work

Example:

<script src="hello.js"></script>
             ^------------------- does not exist.

I hope this helps.

Obrigado, boa sorte

Ajay S :

Thanks a lot for the article. it helped a lot

Ibrahim :

You are welcome @Ajay

Daijobou :

I have checked everything but still the error was there and i can't get it working.

Christian :

Thank you so much. You just saved me the hassle of trying to figure out my bug

usra :

<html>
   <head>
      <link rel="styleSheets" href="style.css">
   </head>
   <body>
      <div id="searchContainer">
     <input class"searchControl" type="text" placeholder="City name or Zipcode" id="searchInput">
     <button class"searchControl" id="searchbtn"> Search </button>
      </div>
      <div id="weatherContainer">
     <div id="weatherDescription">
        <h1 id="cityHeader"></h1>
        <div id="weatherMain">
           <div id="temperature"></div>
           <div id="weatherDescriptionHeader"></div>
           <div> <img id="documentIconImg "></div>
        </div>
        <br>
        <div id="windspeed" class="bottomDetails"></div>
        <div id="humidity" class="bottomDetails"></div>
        <!--now work on js-->
     </div>
      </div>
      <script src="script.js"></script>
   </body>
</html>

or script.js file code is also here:

Let appID = '905925d53d24566c39eef30036b22d33';
Let units = 'imperial';
Let searchMethod = 'Zip';

function searchWeather(searchTerm) {
    fetch(`http://api.openweathermap.org/data/2.5/weather?${searchMethod}=${searchTerm}&appID=${appID}&units=${units}`).then(result => {
    return result.json();
    }).then(result => {
    init(result);
    })
    // fetch api a url bcz its a 
    //call to get information from the API. This link is a queue so searchMethod(a parameter)= searchTerm (parameter value) 
    //wait until we get the info from url/server we use ".then(result=>" 
    //and next converting into json next parse the info which we get from server in init 
}

function init(resultFromServer) {
    console.log(resultFromServer);
}
document.getElementById('searchbtn').addEventListener('click', () => {
    let searchTerm = document.getElementById('searchInput').value;
    if (searchTerm)
    searchWeather(searchTerm);
})

Ibrahim :

@Usra this is not the best way to get help.

If you read the article, you'll see that you may have an error in your path for script.js. Use an absolute path like:

/path/to/script.js

Start with a forward slash / to start at the root of your website.

Dave :

You just saved my life!!!! I had a bug that I NEVER would have found without this. Thank you....

Alex :

Thanks! I have missed that tag several times - you've saved me a few hrs!

Bubu :

Uncaught SyntaxError: Unexpected token { 0.chunk.js:105
Uncaught SyntaxError: Use of const in strict mode.  main.chunk.js:268 

those codes are on console, Localhost3000, when running Node.js, Visual studio code, what should I do?

Bolaji Opemipo Michael :

Just to note again, the / sign is really important. Your browser might get the file in the Network tab (Developers Tools) but it would get it as HTML.

Jan :

Worked like a charm. Thank you.

Martin Ransome :

I am having the same problem: Unexpected token '<'. My error makes no sense.

here is my HTML:

<!DOCTYPE html>
<html>
    <head><title>All Fours Tournament</title></head>
    <body>
        <h1>All Fours</h1>
        <script src = '/cards.js'></script>
        <script src = '/deck.js'></script> 
    </body>
</html>

and here is the server.js:

let express=require('express');
let http=require('http');
let fs=require('fs');

let handleRequest=(request, response)=>{
    response.writeHead(200, {
        'Content-Type':'text/html'
    });
    fs.readFile('allFours.html', null, function(error, data) {
        if(error){
            response.writeHead(404);
            response.write('File Not Found');
        } else {
            response.write(data);
        }
        response.end();
    });
}
http.createServer(handleRequest).listen(4040);
console.log('Server is listening on port 4040');

Please Help.

Ibrahima Diallo :

No matter what the URL is, your server always responds with 'allFours.html'.

Go to http://localhost:4040/cards.js and you will see that it still serves allFours.html

You need to server static files like /cards.js and /deck.js.

Read how to serve static files with express

or with your http handler

Dorian :

Thanks for putting me on the path to fixing a bug!

I had a node.js server responding to a non-existant .js file with a 302 and empty response, instead of 404.

asiaenews :

sir plz make a solution for blogspot/blogger jquery/json errors

Ibrahim :

At @asiaenews it's the same problem and solution everywhere!

Neha :

when i paste the script in console than its shows [Uncaught SyntaxError: Unexpected token '] please help to fix it sir.

dino :

var colors = generateRandomColors(6); var squares = document.querySelectorAll(".square"); var pickedColor = pickColor(); var colorDisplay = document.getElementById("colorDisplay"); var messageDisplay = document.querySelector("#message");

colorDisplay.textContent = pickedColor;

for (var i = 0; i < squares.length; i++){ //add enitial colors to squares squares[i].style.backgroundColor = colors[i];

//add click listeners to squares 
squares[i].addEventListener("click", function(){

//grab color of picked square var clickedColor = this.style.backgroundColor; //compare color to pickedColor if(clickedColor === pickedColor){ messageDisplay.textContent = "Correct!"

changeColors(clickedColor);

}else { this.style.background = "#232323"; messageDisplay.textContent = "Try Again" } }); }

function changeColors(color){ //loop through all squares for ( var i = 0; i < squares.length; i++){ //change each color to match the correct one squares[i].style.backgroundColor = color; }

}

function pickColor(){ var random = Math.floor(Math.random() * (colors.length) ); return colors[random]; }

function generateRandomColors(num){ //make a array var arr = [] // add num random colors to array for (var i=0; i < num; i++){ //getrandomcolor ad push into array arr.push(randomColor())

} //return array return arr; }

function randomColor(){ //pick red from 0-255 var r = Math.floor(Math.random()256); //pick green from 0-255 var g = Math.floor(Math.random()256); //pick blue from 0-255 var b = Math.floor(Math.random()*256); return "rgb(" + r + ", " g + ", " + b + ")"; }

i keep getting Uncaught SyntaxError: Unexpected identifier pls help me

Mafouz DIALLO :

Merci pour cet article!

Let's hear your thoughts

For my eyes only