A place to cache linked articles (think custom and personal wayback machine)
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

index.md 10KB

4 lat temu
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108
  1. title: JavaScript Errors and How to Fix Them
  2. url: http://davidwalsh.name/fix-javascript-errors
  3. hash_url: cfd2bcb75aa201892f2590593f343e39
  4. <p>JavaScript can be a nightmare to debug: Some errors it gives can be very difficult to understand at first, and the line numbers given aren’t always helpful either. Wouldn’t 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!</p>&#13;
  5. <p>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.</p>&#13;
  6. &#13;
  7. <h3>How to read errors?</h3>&#13;
  8. <p>Before the list, let’s quickly look at the structure of an error message. Understanding the structure helps understand the errors, and you’ll have less trouble if you run into any errors not listed here.</p>&#13;
  9. <p>A typical error from Chrome looks like this:</p>&#13;
  10. <pre>Uncaught TypeError: undefined is not a function</pre>&#13;
  11. <p>The structure of the error is as follows:</p>&#13;
  12. <ol>&#13;
  13. <li><strong>Uncaught TypeError</strong>: This part of the message is usually not very useful. Uncaught means the error was not caught in a <code>catch</code> statement, and <code>TypeError</code> is the error’s name.</li>&#13;
  14. <li><strong>undefined is not a function</strong>: 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 <code>undefined</code> like it was a function.</li>&#13;
  15. </ol>&#13;
  16. <p>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 Internet Explorer also give simpler errors than Chrome – but in this case, simpler does not always mean better.</p>&#13;
  17. <p>Now onto the actual errors.</p>&#13;
  18. <h3>Uncaught TypeError: undefined is not a function</h3>&#13;
  19. <p><strong>Related errors:</strong> number is not a function, object is not a function, string is not a function, Unhandled Error: ‘foo’ is not a function, Function Expected</p>&#13;
  20. <p>Occurs when attempting to call a value like a function, where the value is not a function. For example:</p>&#13;
  21. &#13;
  22. <pre class="javascript">var foo = undefined;&#13;
  23. foo();</pre>&#13;
  24. &#13;
  25. <p>This error typically occurs if you are trying to call a function in an object, but you typed the name wrong.</p>&#13;
  26. &#13;
  27. <pre class="javascript">var x = document.getElementByID('foo');</pre>&#13;
  28. &#13;
  29. <p>Since object properties that don’t exist are <code>undefined</code> by default, the above would result in this error.</p>&#13;
  30. <p>The other variations such as “number is not a function” occur when attempting to call a number like it was a function.</p>&#13;
  31. <p><strong>How to fix this error:</strong> Ensure the function name is correct. With this error, the line number will usually point at the correct location.</p>&#13;
  32. <h3>Uncaught ReferenceError: Invalid left-hand side in assignment</h3>&#13;
  33. <p><strong>Related errors:</strong> Uncaught exception: ReferenceError: Cannot assign to ‘functionCall()’, Uncaught exception: ReferenceError: Cannot assign to ‘this’</p>&#13;
  34. <p>Caused by attempting to assign a value to something that cannot be assigned to.</p>&#13;
  35. <p>The most common example of this error is with if-clauses:</p>&#13;
  36. &#13;
  37. <pre class="javascript">if(doSomething() = 'somevalue')</pre>&#13;
  38. &#13;
  39. <p>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 can’t assign to, leading to the error.</p>&#13;
  40. <p><strong>How to fix this error:</strong> Make sure you’re not attempting to assign values to function results or to the <code>this</code> keyword.</p>&#13;
  41. <h3>Uncaught TypeError: Converting circular structure to JSON</h3>&#13;
  42. <p><strong>Related errors:</strong> Uncaught exception: TypeError: JSON.stringify: Not an acyclic Object, TypeError: cyclic object value, Circular reference in value argument not supported </p>&#13;
  43. <p>Always caused by a circular reference in an object, which is then passed into <code>JSON.stringify</code>.</p>&#13;
  44. &#13;
  45. <pre class="javascript">var a = { };&#13;
  46. var b = { a: a };&#13;
  47. a.b = b;&#13;
  48. JSON.stringify(a);</pre>&#13;
  49. &#13;
  50. <p>Because both <code>a</code> and <code>b</code> in the above example have a reference to each other, the resulting object cannot be converted into JSON.</p>&#13;
  51. <p><strong>How to fix this error:</strong> Remove circular references like in the example from any objects you want to convert into JSON.</p>&#13;
  52. <h3>Unexpected token ;</h3>&#13;
  53. <p><strong>Related errors:</strong> Expected ), missing ) after argument list</p>&#13;
  54. <p>The JavaScript interpreter expected something, but it wasn’t there. Typically caused by mismatched parentheses or brackets.</p>&#13;
  55. <p>The token in this error can vary – it might say “Unexpected token ]” or “Expected {” etc.</p>&#13;
  56. <p><strong>How to fix this error:</strong> Sometimes the line number with this error doesn’t point to the correct place, making it difficult to fix.</p>&#13;
  57. <ul>&#13;
  58. <li>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</li>&#13;
  59. <li>Unexpected / is related to regular expressions. The line number for this will usually be correct.</li>&#13;
  60. <li>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</li>&#13;
  61. </ul>&#13;
  62. <h3>Uncaught SyntaxError: Unexpected token ILLEGAL</h3>&#13;
  63. <p><strong>Related errors:</strong> Unterminated String Literal, Invalid Line Terminator</p>&#13;
  64. <p>A string literal is missing the closing quote. </p>&#13;
  65. <p><strong>How to fix this error:</strong> Ensure all strings have the correct closing quote.</p>&#13;
  66. <h3>Uncaught TypeError: Cannot read property ‘foo’ of null, Uncaught TypeError: Cannot read property ‘foo’ of undefined</h3>&#13;
  67. <p><strong>Related errors:</strong> TypeError: someVal is null, Unable to get property ‘foo’ of undefined or null reference </p>&#13;
  68. <p>Attempting to read <code>null</code> or <code>undefined</code> as if it was an object. For example:</p>&#13;
  69. &#13;
  70. <pre class="javascript">var someVal = null;&#13;
  71. console.log(someVal.foo);</pre>&#13;
  72. &#13;
  73. <p><strong>How to fix this error:</strong> Usually caused by typos. Check that the variables used near the line number pointed by the error are correctly named.</p>&#13;
  74. <h3>Uncaught TypeError: Cannot set property ‘foo’ of null, Uncaught TypeError: Cannot set property ‘foo’ of undefined</h3>&#13;
  75. <p><strong>Related errors:</strong> TypeError: someVal is undefined, Unable to set property ‘foo’ of undefined or null reference </p>&#13;
  76. <p>Attempting to write <code>null</code> or <code>undefined</code> as if it was an object. For example:</p>&#13;
  77. &#13;
  78. <pre class="javascript">var someVal = null;&#13;
  79. someVal.foo = 1;</pre>&#13;
  80. &#13;
  81. <p><strong>How to fix this error:</strong> This too is usually caused by typos. Check the variable names near the line the error points to.</p>&#13;
  82. <h3>Uncaught RangeError: Maximum call stack size exceeded</h3>&#13;
  83. <p><strong>Related errors:</strong> Uncaught exception: RangeError: Maximum recursion depth exceeded, too much recursion, Stack overflow </p>&#13;
  84. <p>Usually caused by a bug in program logic, causing infinite recursive function calls.</p>&#13;
  85. <p><strong>How to fix this error:</strong> Check recursive functions for bugs that could cause them to keep recursing forever.</p>&#13;
  86. <h3>Uncaught URIError: URI malformed</h3>&#13;
  87. <p><strong>Related errors:</strong> URIError: malformed URI sequence</p>&#13;
  88. <p>Caused by an invalid decodeURIComponent call.</p>&#13;
  89. <p><strong>How to fix this error:</strong> Check that the <code>decodeURIComponent</code> call at the error’s line number gets correct input.</p>&#13;
  90. <h3>XMLHttpRequest cannot load http://some/url/. No ‘Access-Control-Allow-Origin’ header is present on the requested resource</h3>&#13;
  91. <p><strong>Related errors:</strong> Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://some/url/</p>&#13;
  92. <p>This error is always caused by the usage of XMLHttpRequest.</p>&#13;
  93. <p><strong>How to fix this error:</strong> Ensure the request URL is correct and it respects the <a href="https://developer.mozilla.org/en-US/docs/Web/Security/Same-origin_policy">same-origin policy</a>. A good way to find the offending code is to look at the URL in the error message and find it from your code.</p>&#13;
  94. <h3>InvalidStateError: An attempt was made to use an object that is not, or is no longer, usable</h3>&#13;
  95. <p><strong>Related errors:</strong> InvalidStateError, DOMException code 11</p>&#13;
  96. <p>Means the code called a function that you should not call at the current state. Occurs usually with <code>XMLHttpRequest</code>, when attempting to call functions on it before it’s ready.</p>&#13;
  97. &#13;
  98. <pre class="javascript">var xhr = new XMLHttpRequest();&#13;
  99. xhr.setRequestHeader('Some-Header', 'val');</pre>&#13;
  100. &#13;
  101. <p>In this case, you would get the error because the <code>setRequestHeader</code> function can only be called after calling <code>xhr.open</code>.</p>&#13;
  102. <p><strong>How to fix this error:</strong> 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 <code>xhr.open</code>)</p>&#13;
  103. <h3>Conclusion</h3>&#13;
  104. <p>JavaScript has some of the most unhelpful errors I’ve seen, with the exception of the notorious <code>Expected T_PAAMAYIM_NEKUDOTAYIM</code> 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.</p>&#13;
  105. <p>What’s the most confusing error you’ve seen? Share the frustration in the comments!</p>&#13;
  106. &#13;
  107. <p>Want to learn more about these errors and how to prevent them? <a href="http://davidwalsh.name/eslint">Detect Problems in JavaScript Automatically with ESLint</a>.</p>