Generally speaking, there are two kinds of error you’ll encounter while programming: syntax errors and logic errors. The former is easier to track down, while the latter tends to be more difficult!
For the examples in this post, let’s assume an array of
Imagine we want to check if our
fruits array contains a specific fruit. We could use the modern
includes() method, but let’s use the old-school
indexOf() method for this example.
indexOf() method accepts a value that you want to find in the array. If the value exists, the method will return its index; if not, it will return
So, to check if our
fruits array contains the string
"Kiwi", we could do this:
But imagine we accidentally mistype the
indexOf() method. We could easily find out because the script would throw a
In the following example, notice that I missed the
e in the
The console would show us the error and point us to the relevant line number so we could fix it. For this reason, syntax errors are easier to track down and debug.
In the example above, I accidentally used the less than (
<) operator instead of the greater than (
if statement simply wouldn’t run.
Instead, we’d be banging our heads against the wall, wondering why the hell our code wasn’t working. Tiny logic errors like this are so easy to make, but incredibly tricky to spot!
Planning your scripts on paper
This is why my friend Chris Ferdinandi always recommends planning your scripts on paper:
Before I ever open a text editor or a browser, I plan my script out on paper. It helps me think big picture, and think through the logic of my code before I get bogged down in the specific methods and tactics I need to implement it.
Once you have the logic all mapped out, you can double-check the documentation for the methods you might need.
In the case of our
indexOf() example, we’d be more likely to notice that we need to check if the index is greater than
-1, not less than.
If you have questions, feedback, or any other suggestions, please do email me. I'd love to hear from you!