Tips
Top reasons why your JS code won't work
(so please use the Web Inspector and check for these before you raise your hand):
- You are viewing the wrong HTML file in the browser (or viewing the right file, and editing the wrong file in your text editor)
- You have a syntax error in your code (ex. forgetting to use closing quotes on a string). This always gives you an error in the console when that line of code runs.
- You are calling a non-existent function, which will produce an error in the console.
- You misspelled a property or event name, which will often fail silently (ex.
window.onLoad
instead of window.onload
).
- You are calling a function with
()
when you shouldn't be (for example in an event handler or event listener)
- Your external JS files are in the wrong place.
- If your files are on a server, make sure the file permissions are correct (
644
for files, 755
for folders)
- If you are getting a browser Security Error while using canvas, remember that -
ctx.getImageData()
and ctx.putImageData()
only work from a web server (i.e. not on your local hard drive)
- The value of
this
isn't what you think it is
Best Practices that will help you catch errors
"use strict";
at the top of every <script> tag and JS file will help catch a lot of errors, like forgetting var
when declaring variables.
- Using the strict comparison operator (
===
) rather than the comparison operator (==
) will often prevent errors.
- Use the debugger and set a break point early in the program before the error occurs. Then step through the code line by line and watch the values of your variables.
- Try clearing history or switching browsers.
- Don't be afraid to back up and Start Over! Create a new HTML file and get a "Hello World" JS script working. Then copy-paste pieces of your problematic code and test it.
The bottom line
Remember, most (90%+) of the time the code is malfunctioning, it is doing what you told it to do.