Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript JavaScript Basics (Retired) Introducing JavaScript Where Does JavaScript Go?

Syed Abbas
Syed Abbas
4,762 Points

External javascript file

Hi, when I run my html with external javascript file in chrome, I get an error saying "Uncaught SyntaxError: Invalid or unexpected token" and javascript code does not run but it works fine in inetrnet explorer. I am not sure what the problem is, can you help please. Thank you.

Steven Parker
Steven Parker
231,269 Points

To make it possible to analyze the issue and provide an answer, please post your code here. And be sure to format it using the instructions from the Markdown Cheatsheet found below the "Add an Answer" area :arrow_heading_down:

4 Answers

Syed Abbas
Syed Abbas
4,762 Points

Please find below the code which is a very basic HTML and a single line of javascript code. The error message which I get in console of the Chrome is at the end. <!DOCTYPE html> <html> <head> <title>HTML Forms</title> <script src="script.js"></script>
</head> <body>
</body> </html>

alert("hello");

Uncaught SyntaxError: Invalid or unexpected token

Thank you.

Steven Parker
Steven Parker
231,269 Points

It looks like you forgot the "script" tags.

When inserting JavaScript into an HTML file, it must be enclosed in script tags, like this:

<script>
    alert("hello");
</script>

Also, all of this should be placed before the end </body> tag.

Next time, remember to format your code with Markdown.


If your code is in a separate file you still need script tags, but with a special attribute to load in your other file:

<script src="script.js"></script>

This would also go before the end tag of the body. Also, if you're working with the courses, the JavaScript files are often in a separate folder named "js". In that case you would use "js/script.js" as the name.

Syed Abbas
Syed Abbas
4,762 Points

Sorry I forgot to mention that my javascript code is in a separate javascript file called 'script.js'.

Steven Parker
Steven Parker
231,269 Points

Then I'm not sure why you would get a "Uncaught SyntaxError: Invalid or unexpected token" error. Or do you have the HTML code in that file with it?

But see the addition to my answer above.

Syed Abbas
Syed Abbas
4,762 Points

Ok that's fine. I'll look into it more. Thank you for your time.