Have you ever wondered why your code isn't working? What does that dreadful red message mean? Don't worry that message is there to help you. Let's begin with some of the common errors you will encounter or may have already seen.
Error Types
The errors you face will generally be a syntax error or a logic error.
Syntax Errors
These errors are quite easy to fix because you will receive a message stating where the error occurred and what the error is.
The message starts off by providing the path to the error.
The path leads us to the 'index.js' file. The number '1' tells us that the error is on the first line of the 'index.js' file. Depending on which integrated development environment (IDE) you are using there may be a colon and a second number next to the first number indicating the character where the error starts.
Awesome! Now we know for sure that we have a syntax error. Unexpected identifier? What does that mean? Recall what we are doing on this line. We want to declare a variable with 'const'. Usually the problem is a misspelled word so let's check our spelling.
Looks like we misspelled 'const'. The 's' is missing! Let's fix it and see if that solves the problem.
Nice now our program is working and the error message is gone! Unexpected identifier is just one of the many syntax errors. If you would like to learn about all of the different types of syntax errors including range errors and type errors, I recommend visiting mdn web docs.
Logic Errors
Now the errors that don't often involve a message. A syntax error stops the program part way through or prevents the program from running at all. Logic errors don't behave the same way. The program works but the results are not what we wanted or expected.
We want to make a program that returns a random number from 1 to 50. The problem is the program always returns 1. We didn't get a error message so we know there aren't any syntax errors. Let's backtrack and look at each part of the program.
Math.random() returns a random decimal number between 0 and 1.
Math.floor() rounds a number down.
The above code will always return 0 since Math.random() returns a decimal number between 0 and 1. So let's add 1 to always have it return a value of 1.
Before we round the random number down we first need to multiply it by 50.
Perfect, the program works! When you encounter a logic error you have to think about what you want your program to accomplish. If you aren't getting the expected results then dig into where you believe the error is and start dissecting your code.
Conclusion
As a beginner you will run into many errors but don't let that discourage you. Error messages are not something to fear but rather something to be comfortable with. They are there to help you achieve the results you are looking for.
Top comments (0)