You are on page 1of 18

9/21/2017 Strange JavaScript Errors and How to Fix Them

JavaScript Errors and How to FixThem

By Jani Hartikainenon January 22, 2015 26

JavaScript can be a nightmare to debug: Some errors it gives can be very difficult to understand
at first, and the line numbers given arent always helpful either. Wouldnt it be useful to have a
list where you could look to find out what they mean and how to fix them? Here you go!

Below is a list of the strange errors in JavaScript. Different browsers can give you different
messages for the same error, so there are several different examples where applicable.

How to read errors?


Before the list, lets quickly look at the structure of an error message. Understanding the
structure helps understand the errors, and youll have less trouble if you run into any errors
not listed here.

A typical error from Chrome looks like this:

Uncaught TypeError: undefined is not a function

The structure of the error is as follows:

1. Uncaught TypeError: This part of the message is usually not very useful. Uncaught
means the error was not caught in a catch statement, and TypeError is the errors
name.
2. undefined is not a function: This is the message part. With error messages, you have to
read them very literally. For example in this case it literally means that the code
attempted to use undefined like it was a function.

Other webkit-based browsers, like Safari, give errors in a similar format to Chrome. Errors
from Firefox are similar, but do not always include the first part, and recent versions of
https://davidwalsh.name/fix-javascript-errors 1/18
9/21/2017 Strange JavaScript Errors and How to Fix Them

Internet Explorer also give simpler errors than Chrome but in this case, simpler does not
always mean better.

Now onto the actual errors.

Uncaught TypeError: undefined is not a function


Related errors: number is not a function, object is not a function, string is not a function,
Unhandled Error: foo is not a function, Function Expected

Occurs when attempting to call a value like a function, where the value is not a function. For
example:

var foo = undefined;


foo();

This error typically occurs if you are trying to call a function in an object, but you typed the
name wrong.

var x = document.getElementByID('foo');

Since object properties that dont exist are undefined by default, the above would result in
this error.

The other variations such as number is not a function occur when attempting to call a
number like it was a function.

How to fix this error: Ensure the function name is correct. With this error, the line number
will usually point at the correct location.

Uncaught ReferenceError: Invalid left-hand side in assignment


Related errors: Uncaught exception: ReferenceError: Cannot assign to functionCall(),
Uncaught exception: ReferenceError: Cannot assign to this

Caused by attempting to assign a value to something that cannot be assigned to.

https://davidwalsh.name/fix-javascript-errors 2/18
9/21/2017 Strange JavaScript Errors and How to Fix Them

The most common example of this error is with if-clauses:

if(doSomething() = 'somevalue')

In this example, the programmer accidentally used a single equals instead of two. The message
left-hand side in assignment is referring to the part on the left side of the equals sign, so like
you can see in the above example, the left-hand side contains something you cant assign to,
leading to the error.

How to fix this error: Make sure youre not attempting to assign values to function results or
to the this keyword.

Uncaught TypeError: Converting circular structure to JSON


Related errors: Uncaught exception: TypeError: JSON.stringify: Not an acyclic Object,
TypeError: cyclic object value, Circular reference in value argument not supported

Always caused by a circular reference in an object, which is then passed into JSON.stringify .

var a = { };
var b = { a: a };
a.b = b;
JSON.stringify(a);

Because both a and b in the above example have a reference to each other, the resulting
object cannot be converted into JSON.

How to fix this error: Remove circular references like in the example from any objects you
want to convert into JSON.

Unexpected token ;
Related errors: Expected ), missing ) after argument list

The JavaScript interpreter expected something, but it wasnt there. Typically caused by
mismatched parentheses or brackets.

https://davidwalsh.name/fix-javascript-errors 3/18
9/21/2017 Strange JavaScript Errors and How to Fix Them

The token in this error can vary it might say Unexpected token ] or Expected { etc.

How to fix this error: Sometimes the line number with this error doesnt point to the correct
place, making it difficult to fix.

An error with [ ] { } ( ) is usually caused by a mismatching pair. Check that all your
parentheses and brackets have a matching pair. In this case, line number will often point
to something else than the problem character
Unexpected / is related to regular expressions. The line number for this will usually be
correct.
Unexpected ; is usually caused by having a ; inside an object or array literal, or within the
argument list of a function call. The line number will usually be correct for this case as
well

Uncaught SyntaxError: Unexpected token ILLEGAL


Related errors: Unterminated String Literal, Invalid Line Terminator

A string literal is missing the closing quote.

How to fix this error: Ensure all strings have the correct closing quote.

Uncaught TypeError: Cannot read property foo of null, Uncaught


TypeError: Cannot read property foo of undefined
Related errors: TypeError: someVal is null, Unable to get property foo of undefined or null
reference

Attempting to read null or undefined as if it was an object. For example:

var someVal = null;


console.log(someVal.foo);

How to fix this error: Usually caused by typos. Check that the variables used near the line
number pointed by the error are correctly named.

Uncaught TypeError: Cannot set property foo of null, Uncaught


TypeError: Cannot set property foo of undefined

https://davidwalsh.name/fix-javascript-errors 4/18
9/21/2017 Strange JavaScript Errors and How to Fix Them

Related errors: TypeError: someVal is undefined, Unable to set property foo of undefined or
null reference

Attempting to write null or undefined as if it was an object. For example:

var someVal = null;


someVal.foo = 1;

How to fix this error: This too is usually caused by typos. Check the variable names near the
line the error points to.

Uncaught RangeError: Maximum call stack size exceeded


Related errors: Uncaught exception: RangeError: Maximum recursion depth exceeded, too
much recursion, Stack overflow

Usually caused by a bug in program logic, causing infinite recursive function calls.

How to fix this error: Check recursive functions for bugs that could cause them to keep
recursing forever.

Uncaught URIError: URI malformed


Related errors: URIError: malformed URI sequence

Caused by an invalid decodeURIComponent call.

How to fix this error: Check that the decodeURIComponent call at the errors line number gets
correct input.

XMLHttpRequest cannot load http://some/url/. No Access-Control-


Allow-Origin header is present on the requested resource
Related errors: Cross-Origin Request Blocked: The Same Origin Policy disallows reading the
remote resource at http://some/url/

This error is always caused by the usage of XMLHttpRequest.

https://davidwalsh.name/fix-javascript-errors 5/18
9/21/2017 Strange JavaScript Errors and How to Fix Them

How to fix this error: Ensure the request URL is correct and it respects the same-origin
policy. A good way to find the offending code is to look at the URL in the error message and
find it from your code.

InvalidStateError: An attempt was made to use an object that is not,


or is no longer, usable
Related errors: InvalidStateError, DOMException code 11

Means the code called a function that you should not call at the current state. Occurs usually
with XMLHttpRequest , when attempting to call functions on it before its ready.

var xhr = new XMLHttpRequest();


xhr.setRequestHeader('Some-Header', 'val');

In this case, you would get the error because the setRequestHeader function can only be called
after calling xhr.open .

How to fix this error: Look at the code on the line pointed by the error and make sure it runs
at the correct time, or add any necessary calls before it (such as xhr.open )

Conclusion
JavaScript has some of the most unhelpful errors Ive seen, with the exception of the notorious
Expected T_PAAMAYIM_NEKUDOTAYIM in PHP. With more familiarity the errors start to make more
sense. Modern browsers also help, as they no longer give the completely useless errors they
used to.

Whats the most confusing error youve seen? Share the frustration in the comments!

Want to learn more about these errors and how to prevent them? Detect Problems in
JavaScript Automatically with ESLint.

About Jani Hartikainen


Jani Hartikainen has spent over 10 years building web applications. His clients include
companies like Nokia and hot super secret startups. When not programming or playing
games, Jani writes about JavaScript and high quality code on his site.

https://davidwalsh.name/fix-javascript-errors 6/18
9/21/2017 Strange JavaScript Errors and How to Fix Them

codeutopia.net jhartikainen posts

Recent Features
Write Better JavaScript withPromises
You've probably heard the talk around the water cooler about how promises are the future. All
of the cool kids are using them, but you don't see what makes them so special. Can't you just
use a callback? What's the big deal? In this article, we'll...

Animated 3D Flipping Menu withCSS


CSS animations aren't just for basic fades or sliding elements anymore -- CSS animations are
capable of much more. I've showed you how you can create an exploding logo (applied with
JavaScript, but all animation is CSS), an animated Photo Stack, a sweet...

Incredible Demos
HTML5 Input TypesAlternative
As you may know, HTML5 has introduced several new input types: number, date, color, range,
etc. The question is: should you start using these controls or not? As much as I want to say
"Yes", I think they are not yet ready for any real life...

HTML5 Placeholder Styling withCSS


Last week I showed you how you could style selected text with CSS. I've searched for more
interesting CSS style properties and found another: INPUT placeholder styling. Let me show
you how to style placeholder text within INPUT elements with some unique CSS code. The
CSS Firefox...

Discussion

Sergey Gospodarets
https://davidwalsh.name/fix-javascript-errors 7/18
9/21/2017 Strange JavaScript Errors and How to Fix Them

To avoid RangeError errors- the best way might be changing recursions to loops, because
browsers have limitations for JavaScript call stack- which is usually from 1525 (IE) to 334028
(FF).
I prepared demo to check it in your browser:

http://codepen.io/malyw/pen/pvwoyK

HTML CSS JS Result Edit on

JavaScript call stack limitation test


>> Starting recursion with depth: 100000
>> A "Range Error" was thrown
>> 10462 recursions have been done- it's the current
browser call stack limitation
>> 100000 loops have been done

Some Math calculation might take more cycles- so its good idea to change them to loops
and move e.g. to Web Workers.

Jani Hartikainen
Thats a great tip Sergey. Its true that in some algorithms, its possible to run into the
recursion limitations without a bug.

cbloss793
This article nails JavaScript errors right on the head. Especially the one about the
Unexpected[] or {}. Ive had that point to the jQuery library when it was just within my own
code!

Thanks for sharing!

Till
You can eliminate a lot of these errors by using a linter like jshint or eslint. Its useful to
have a linter in your build process as well as in your editor.

Jani Hartikainen

https://davidwalsh.name/fix-javascript-errors 8/18
9/21/2017 Strange JavaScript Errors and How to Fix Them

Yeah, Ive been looking at these kinds of tools lately. Others like Flow and TypeScript
could also be useful, though may require a bit more work to set up.

Definitely a topic I might write about in the future!

gotofritz
Ive been looking at these kinds of tools lately? Wow, I thought they were standard
practice in the industry nowadays, does anyone really still run their code without
checking it with some tool first?

For what is worth, eslint is vastly superior to jshint more rules (and the ability to write
your own), and it differentiates between errors and warnings (so you dont have to stop a
build because of unimportant formatting).

Gepphorn Feco
I had similar experience for Javascript, and decided the problem was with the actual
language itself. I realise that there is not much point to use Javascript when there are
languages available which are not limited and broken and are a pleasure to use and jebug.

Sarfaraz Ansari
Wow! good information very nice article I hope it helps me a lot thanks for sharing

Cathy Mayhue
Thanks for this very helpful article. Locating and rectifying error in a large Javascript code
has been hugely frustrating, I some times prayed for the day, when some body develops a
compiler, interpreter or any helpful tool to help us debug and remove errors.

Michaux Kelley
Great article! Also, I agree with Till about using a linter like JSHint. Its one way to save page
reload time, typing to open the console, finding the correct line where the error occurred,
deciphering some of the more cryptic error messages in certain browsers, and teaching good
practices when the linter is configured correctly.

Bhumi
Very useful.Thanks!

Todd Gardner

https://davidwalsh.name/fix-javascript-errors 9/18
9/21/2017 Strange JavaScript Errors and How to Fix Them

Awesome article, well done. What further complicates the problem is that each browser has
implemented {object Error} in a different way! The behavior and contents change wildly
browser to browser. I did a talk on these differences last year:

http://vimeo.com/97537677

Running a JavaScript Error Logging service ( http://Trackjs.com ), weve seen tons of crazy
errors. Sometimes devices or plugins overload behavior and use JavaScript as a transport
layer. For example, Chrome on IOS overloads XmlHttpRequest with extra properties and
uses it to communicate to the native webkit client. If you mess with the XmlHttpRequest
on this platform, chrome shows tons of nasty security errors!

Blade
A code highlighting editor will pretty much make almost all of these errors except the
circular JSON reference go away.

Blade
er.. and the other runtime errors that i didnt notice at first glance. :-D

James Edwards
Be grateful you dont still have to code for IE6, and its notoriously unhelpful unspecified
error at line 1 :-O

Mpara Faith
Thanks a bunch. Saved me a lot of stress

Neil
Hi David,

Im getting an Uncaught TypeError when a response from a jsonp request is received after
the timeout I specified. Most of the time it works. However, there are times that our api
server is so heavily busy. How do I catch the error rather than seeing Uncaught TypeError in
the console?

Thanks! Great site!

Neil

oleg

https://davidwalsh.name/fix-javascript-errors 10/18
9/21/2017 Strange JavaScript Errors and How to Fix Them

9112334024676320 + 1 === 9112334024676320


//=> true
//in node,chrome,firefox

John
Internet Explorer is generating the error Unable to get property chunkSize of undefined
or null reference. What does that mean?

Edaddou
I keep in running into
ORIGINAL EXCEPTION: TypeError: Cannot read property request of undefined

Mike
Hi, I have a problem, that I dont understand. I am using angular/D3/Typescript in a class
that creates a chart. I use d3.evet.clientX and all is well, but in my controller it is undefined.
why?

Thanks Mike

Stu
IE9 has just offered this pair of doozies with absolutely no reference to whatever the issue is,
so 7,000 possible lines of code to sift through. Fun :-|

SyntaxError: Invalid character


{
[functions]: ,
description: "Invalid character",
message: "Invalid character",
name: "SyntaxError",
number: -2146827274
}

undefined
TypeError: Unable to get property 'Message' of undefined or null reference
{
[functions]: ,
description: "Unable to get property 'Message' of undefined or null reference",
message: "Unable to get property 'Message' of undefined or null reference",
name: "TypeError",

number: -2146823281
}

https://davidwalsh.name/fix-javascript-errors 11/18
9/21/2017 Strange JavaScript Errors and How to Fix Them

Stu
Not a js error though,

fixed the issue. Head banging time finished.

Stu
<meta http-equiv=X-UA-Compatible content=IE=edge>

Jaay
hi,

Even though included necessary files am following error

{Uncaught TypeError: Cannot read property encode of undefined}

am trying to create front end code editor for python mode but couldnt make it. have had
following this example to compile and execute the code.

http://qnimate.com/create-an-frontend-editor-with-code-highlighting-and-execution/

could anyone help me to fix it?

Looking forward

Robert
Dear Jay,

A look at this error would help

/home/pi/firebase.js:27
Raspistill.on('close',(code) => {
^
SyntaxError: Unexpected token >
at Module._compile (module.js:439:25)
at Object.Module._extensions..js (module.js:474:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)
at Function.Module.runMain (module.js:497:10)
at startup (node.js:119:16)
at node.js:906:3

Thanks, Aldo

https://davidwalsh.name/fix-javascript-errors 12/18
9/21/2017 Strange JavaScript Errors and How to Fix Them

Name Email Website

Wrap your code in <pre class="{language}"></pre> tags, link to a GitHub gist, JSFiddle fiddle, or
CodePen pen to embed!

Continue this conversation via email

Post Comment! Use Code Editor

https://davidwalsh.name/fix-javascript-errors 13/18
9/21/2017 Strange JavaScript Errors and How to Fix Them

https://davidwalsh.name/fix-javascript-errors 14/18
9/21/2017 Strange JavaScript Errors and How to Fix Them

https://davidwalsh.name/fix-javascript-errors 15/18
9/21/2017 Strange JavaScript Errors and How to Fix Them

https://davidwalsh.name/fix-javascript-errors 16/18
9/21/2017 Strange JavaScript Errors and How to Fix Them

https://davidwalsh.name/fix-javascript-errors 17/18
9/21/2017 Strange JavaScript Errors and How to Fix Them

https://davidwalsh.name/fix-javascript-errors 18/18

You might also like