Undefined and Undeclared in JavaScript Tutorial

In this section, we will learn what the undefined and undeclared means and their implementations in JavaScript.

What is Undefined in JavaScript? And What Does Undefined Mean?

By default, when we first create a variable in JavaScript and don’t initialize it with a value, that variable will get the value `undefined`.

The `undefined` value basically means the target variable does not have a value stored to it yet.

Example: undefined value in JavaScript

let name;

console.log(name);

Output:

undefined

How to check undefined in JavaScript? JavaScript Undefined and typeof Operator

We can use the `typeof` operator to check and see if the current value of a variable is undefined.

If you’re not familiar with the typeof operator, please check the related section. But in short, we put the target variable on the right side of this operator and it will return a value of type string, declaring the type of the value that is stored in the target variable.

Example: check if undefined in JavaScript via if statement

let name; 
if (typeof name == "undefined"){
  document.getElementById("output").innerText = `There's no value in the 'name' variable`;
}else{
  document.getElementById("output").innerText =`${name}`;
}

What is JavaScript Undeclared?

In JavaScript, if we try to access the value of a variable that does not exist, we will get the undeclared error.

Undeclared means the target variable that we’re attempting to access is not in the program or is not in a scope accessible to the part that is currently executing.

Example: throwing undeclared error in JavaScript

console.log(fullName);

Output:

Uncaught ReferenceError: fullName is not defined

In this example, do you see the declaration of the `fullName` variable? Basically, do you see any `let fullName;` or `var fullName` or `const fullName` statement? Obviously not!

Even though the `fullName` variable is not declared, we tried to get the value of the variable. In a situation like this, the compiler will return to us the type of error you see on the output.

Note: These types of errors usually appear on the web browser’s console. So you need to open your browser’s console to see the error.

In the Scope section, we will explain this in more detail.

Facebook
Twitter
Pinterest
LinkedIn

Top Technologies