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(33)

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!

Bimby :

Thanks. this helped

Edwin G :

Thanks -- i kept seeing this error and could not figure out where this came from. My code generated a src= link to the root directory without any js filename at all. So it returned the (index):1

phineas gage :

Thank you. Very helpful!

I had pasted the .js file inside the project folder on the file system but did not refresh the folder inside Visual Studio so the .js file was not being included in the project.

Divya Sirigireddy :

Hi I have an error named unexpected token "<" can anyone help me out.

const cartBtn = document.querySelector(".cart-btn");
const closeCartBtn = document.querySelector(".close-cart");
const clearCartBtn = document.querySelector(".clear-cart");
const cartDOM = document.querySelector(".cart");
const cartOverlay = document.querySelector(".cart-overlay");
const cartItems = document.querySelector(".cart-items");
const cartTotal = document.querySelector(".cart-total");
const cartContent = document.querySelector(".cart-content");
const ProductsDOM = document.querySelector(".products-center");
// cart
let cart = [];

// getting the products
class Products{
async getProducts()
{
        try {
            let result = await fetch("products.json");
            let data = await result.json();
            let products = data.items;
            products = products.map(item => {
                const {title,price} = item.fields;
                const id = item.sys;
                const image = item.fields.image.fields.file.url;
                return {title,price,id,image}
            });
            return products;
        }
        catch (error) {
        console.log(error);
        }
  }
}

// display products

class UI {
displayProducts(products){
let result = "";
products.forEach(product => {
    result +=
    //single product 
    <article class ="product"> // error comes here
            <div class="img-container">
                <img src= ${product.image} class="product- 
            img" />
                <button class="btn" data-id= ${product.id} 
                  >
                    <i class="fas fa-shopping-cart"></i>add 
                    to cart
                </button>
            </div>
            <h3>${product.title}</h3>'
            <h4>$${product.price}</h4>
    </article>

});
ProductsDOM.innerHTML = result ;
}
}


// local storage
class Storage{

}
document.addEventListener("DOMContentLoaded", () => {
    let ui = new UI();
    let products = new Products();
    products.getProducts().then(products => ui.displayProducts(products));

});

Anonymous :

Thanks.

yannis :

Bonjour, j'ai un probléme que je ne comprends pas, le voici, jeton inattendu '<', voici mon html

<html lang='<?php echo  CURRENT_LANG ?>'>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <meta http-equiv="Content-language" content="fr" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?php if ($_GET['controller']!='admin') require "title.view.php"; ?></title>

et un autre concernant : Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects to the end user's experience. For more help, check https://xhr.spec.whatwg.org/. https://www.webtransportdeal.com/assets/plugins/jquery-2.1.4.min.js:4

merci de bien vouloir m'aider svp

Nandik Devbhuti :

For the error: " Uncaught SyntaxError: Unexpected token < "

If you are creating React websites and in console, you saw this kind of error, however, your site is running, as usual, the main thing is that while attaching the source path to the script tag, you must have missed the type attribute -> type="text/jsx". Correcting this should rectify your error.

Echo :

So you're saying I'm getting this because the file isn't in the library? For instance, I'm trying to call a counter and since it's not in the jQuery library I'm getting this error?

 $( document ).ready( function(){
// Call counter and set autostart to false
$( .stats ).count( {
    autoStart: false 
});

// Call horizon
$( '.stats' ).horizon({
 recurring: true, 

// Start counter once element is in view
inView: function(){ 
        $( '.stats' ).each( function(){
        var count = $( this ).data( 'counter' );
            count.startCount();
        });
    },

// Clear counter once element is out of view
outOfView:  function(){ 
        $( '.stats' ).each( function(){
        var count = $( this ).data( 'counter' );
            count.clearCount();
        });
    }
});
});

Ivan :

Right on the spot! Thanks a lot!

Mina :

``` function performAction(c){ const newZip = document.getElementById('zip').value; const newFeeling = document.getElementById('feelings').value; getWeather(baseURL , newZip ,apiKey ); .then(function(data){ postData('/all' , {temp:data.list[0].main , date:newDate , response:newFeeling}); updateApp(); //console.log(updateApp); });

}; ```

it giving me an error in .then function and i donot know why

rothfeller :

Thank you, braza! Your HELP helped a lot! -))

by binding the script, I added the style.css document to the <script src="style.css"></script> The mistake can be everywhere -))

Aditya :

Hello, I might have a similar problem - Uncaught SyntaxError: unexpected token: ':', and it also shows error to the HTML page's first line -

<!DOCTYPE html>

And I also verified the path of the js files and it seems correct.

Please help!

Let's hear your thoughts

For my eyes only