We learn how to handle errors in JS…
Error
Refer -> Error Reference - MDN Web Docs
An error is an object that points out something wrong in our code. It consists of a name / type and a message.
Consider the following code :
let text = `Take me to church
I shall worship like a dog
At the shrine of your lies
I'll tell you my sins
So you can sharpen your knife
Offer me that deathless death
Good God, let me give you my life`;
let counter = 0;
for (let i=0; i<=text.length; i++)
{
if (str=='a' || str=='e' || str=='i' || str=='o' || str=='u')
{
counter++;
}
}
console.log("Number of vowels: " + counter);
//ReferenceError: str is not defined
When we compile this program, JS immediately slaps us with a ReferenceError
. This very act is called ‘throwing’ an error and it helps us understand where we went wrong.
Let’s analyse the error message.
ReferenceError: str is not defined at Object.<anonymous> (...\js\helyo.js:12:5)
A ReferenceError
occurs when a variable [left undeclared or un-initialised] is being used in a statement. Simply said, we haven’t defined the variable at all!
Next, it shows the location of the file along with the exact line and character where the compiler encounters the error.
Syntax error
Let’s see another program and try to spot the error in it :
const prompt = require("prompt-sync")({sigint:true});
const num = prompt(Enter a number: );
for (let i=1; i<=num; i++)
{
if (i%3===0 && i%5===0)
{
console.log("FizzBuzz");
}
else if (i%5===0)
{
console.log("Buzz")
}
else if (i%3===0)
{
console.log("Fizz")
}
else
{
console.log(i)
}
}
/*
...\js\ohohoh.js:4
const num = prompt(Enter a number: );
^^^^^
SyntaxError: missing ) after argument list
*/
Looks like we forgot the quote marks in the prompt()
function. This causes a SyntaxError
and the program ceases to run until it’s resolved.
This error occurs when we don’t follow a language’s proper syntax.
Type error
This error occurs due to 3 different causes. Let’s see them one-by-one.
let song = "Winter of Our Youth"
let len = song.length;
console.log(len.split())
/*
TypeError: len.split is not a function
at Object.<anonymous> (...\js\ohohoh.js:6:17)
*/
The compiler throws a TypeError
at us when we try to call a String
function using a number
variable. Since those types are definitely incompatible, this error occurs.
Now if we try to cast the variable to String
…
let song = "Winter of Our Youth"
let len = String(song.length);
console.log(len.split())
//[ '19' ]
Now let’s see the second scenario :
const prompt = require("prompt-sync")({sigint:true});
prompt = "";
console.log(prompt);
/*
TypeError: Assignment to constant variable.
at Object.<anonymous> (...\js\ohohoh.js:4:8)
*/
Remember when we spoke about const
variables? Since their value cannot be changed, JS throws TypeError
at us when we try to change its value.