Errors In Javascript

Syntax Error vs. Reference Error vs. Type Error

ยท

2 min read

Errors In Javascript

Errors are like a by-product of coding. Like any other programming language, errors are also present in javascript. Let's look at basic errors in javascript.

1. Syntax Error

In the programming language way of writing code called syntax, Javascript also has its own syntax to write code. and if you messed up with that syntax javascript engine will throw a syntax error.

For example,

let a = 10;
let a = 20;

Javascript will throw an error like this, syntax error.png

In the above example, we declaring the variable a two times in the same scope, which is not allowed in javascript syntax because a variable with the same name has already been declared.


2. Reference Error

When we declare a variable javascript engine assigns memory for that variable. After when we want to access that variable javascript will look for a reference in memory for it. If it's not able to find a reference it will give a reference error.

For example,

console.log(a);
let a = 10;

reference error.png

In the above example, we are trying to access the variable a before declaring it, so the javascript engine is not able to get a reference for that hence it throwing a reference error.


3. Type Error

Javascript is a dynamically typed language, which means you can store any type of data in any variable at a time. But only with let we can have this freedom, there is one more way we can declare a variable in modern javascript which is using const. As the name suggests it's going to be a constant variable which means you are can't change the value later in the program. If you do then let's see, what happens.

For example,

const a = 10;
a = 20;

type error.png

In the above example, we are trying to reassign value to a variable a which is not allowed for contact variable type, hence the javascript engine will throw a type error.


TL;DR

  1. Syntax Error: If you are messed with javascript syntax.
  2. Reference Error: If you are trying to access a variable before declaring it.
  3. Type Error: If you are trying to reassign a value to a constant variable.

Thanks for reading. ๐Ÿ˜Š

ย