Skip to main content

Command Palette

Search for a command to run...

Syntax error, Type error & Reference error in JavaScript

JavaScript errors

Published
•2 min read•View as Markdown
Syntax error, Type error & Reference error in JavaScript

What is an error?

Error is a part of code that is not correct. Usually, when the developer writes code then by mistake some rules are violated as per the set of rules of the programming language, at the end which generates an error.

There are so many types of errors that can be recognized by the specific types and names, some of them are:-

  • Syntax error

  • Type error

  • Reference error


1. Syntax error in JavaScript

In programming, there are some sets of rules and the way of writing code which is called syntax. And if the way (set of rules and instructions) of writing code is violated then it generates a syntax error.

For example:

const printMyName = () => {console.log("Zeeshan"}

The above code will result in a syntax error:

The reason for the error is that, ) is missing in the console.log() . And we can easily debug the error in the console as shown above.


2. Type error in JavaScript

Javascript is a dynamically typed language, which means you can store any type of data in any variable at a time. But this freedom comes only with let keyword and there is also another way to declare variables in ES6 (modern JavaScript) which is const keyword. const keyword is constant as the name suggests, the value of the constant variable can't be changed through reassignment (through assignment operator) or it can't be redeclared with the same variable name.

And if we try to do reassignment then this will result in the type error.

For example:

const a = "Zeeshan";
a = "John"  //Reassignment in variable

The above code will throw a TypeError due to reassignment.


3. Reference error in JavaScript

For every variable we declare, the JavaScript engine assigns memory to that variable. So, whenever 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 ReferenceError . This error occurs when a variable that doesn't exist is referenced.

ReferenceError also occurs when we try to access a variable before declaring it because the JavaScript engine does not find any reference memory related to that variable.

For example:

console.log(firstName); //firstName variable is called before declaration.
const firstName = "Tanay";

The above code will throw a ReferenceError as it is being called before the declaration.


Thanks for reading 😊.

K

Awesome explanation cartoon for errors

1
Z

Thank you ❣️

1