No matter how good of a programmer you are, it is impossible to prevent errors in your program.And they might not necessarily be your fault, especially when dealing with user input. The data that the user provides might not make sense.
By default, when JavaScript encounters an error, the program terminates. For example, the following code calculates the sum of all items in an array.
1let userInput = [1, 2, 3];
2
3let sum = 0;
4
5userInput.forEach((element) => {
6 sum = sum + element;
7});
8
9console.log(sum);
16
If the user provides an invalid input, such as null
, an error will be returned, and the program will terminate.
1let userInput = null;
2
3let sum = 0;
4
5userInput.forEach((element) => {
6 sum = sum + element;
7});
8
9console.log(sum);
1/Users/. . ./index.js:5
2userInput.forEach((element) => {
3 ^
4
5TypeError: Cannot read properties of null (reading 'forEach')
6 at Object.<anonymous> (/Users/. . ./index.js:5:11)
7 . . .
8
9Node.js v21.6.0
Notice that the program terminates at forEach()
, where the error occurs. The rest of the code is simply ignored.
The try catch block
But this is obviously not the best solution. You don't want the user's false input to crush your entire program. Instead, you could use a try catch
block, which tells JavaScript to try something first, catch the error if that doesn't work, and then move on to something else. For instance: