You are currently viewing 3 Best Ways to Check if Variable is Defined in JavaScript

3 Best Ways to Check if Variable is Defined in JavaScript

Javascript Check if Variable is Defined

In this article we will discuss various ways to check if a variable is defined in JavaScript and avoid errors that can arise from using undefined variables.

Why do we need to check if a variable is defined?

Checking if a variable is defined in JavaScript is important for several reasons:

  • If we try to use an undefined variable, it will result in a runtime error. So,checking if the variable is defined beforehand can help prevent such errors.
  • If you are working with user input, you need to check if a particular field exists before accessing its value.
  • In some cases, variables may not always contain a value, and in such cases, we need to check if variable is defined before using it. For example, if you’re working with an API response that may or may not contain a certain property, So you’ll need to check if the property is defined.

Some Methods to check if variable is defined

If a variable can be declared but not initialized, it means that memory space has been allocated but no value has been assigned to it. If you try to use an uninitialized variable, you will get an error message, and if a variable is not declared, you will also get an error message.

To avoid these errors, you must check whether a variable is defined or not before using it in your code. Here are some ways to do this:

1. Using typeof :

The typeof operator in JavaScript returns a string that indicates the type of the operand. For example, if we apply the typeof operator to the number ’42’, we get the string “number”. Similarly if we use typeOf operator for variable which has string value, we will get the string “string”. Same as If we apply it to a variable that has not been defined, we will get the string “undefined”.

READ ALSO  3 Simple Ways to Sum Array of Objects in JS

To check if a variable is defined, we can use the ‘typeof’ operator and compare the result to the string “undefined”.

var myVariable;   // variable declaration
if (typeof myVariable !== 'undefined') {
  console.log('myVariable is defined');
} else {
  console.log('myVariable is not defined');
}

// Output: myVariable is not defined

In this above example, we declared variable ‘myVariable’. Then we use the ‘typeof’ operator to check if ‘myVariable’ is defined or not. We haven’t defined the ‘myVariable’ variable, so it execute else block and return ‘myVariable is not defined’.

 

var myVariable = 'Welcome';  //variable initialization/defined
if (typeof myVariable !== 'undefined') {
  console.log('myVariable is defined');
} else {
  console.log('myVariable is not defined');
}

// Output: myVariable is defined

In this example, we initialized/defined ‘myVariable’ because have assigned the string “Welcome”. Here, the ‘typeof’ operator returns ‘string’, So the code inside the if block is executed and “myVariable is defined” is logged to the console.

2. Using the “in” operator

We can also use the “in” operator to check if a variable is defined or not and it is one of the simplest ways. We use the ‘window’ object with the ‘in’ operator. ‘window’ object is a global object and it checks variable exists in the global object. If it exists, then the variable is defined, otherwise the variable is not defined.

var myVariable = 'Hello, world!'; // variable defined

if ("myVariable" in window) {
  document.write("variable is defined")
}else{
   document.write("variable is not defined")
}

// Output: myVariable is defined

// myVariable is not defined

 

if ("myVariable" in window) {
  document.write("variable is defined")
}else{
   document.write("variable is not defined")
}
// Output: myVariable is defined

Note : This method only works for checking only global variables are defined. It will not work for checking if local variables or variables declared inside a function are defined. In those cases, you should use the typeof operator, as I explained in my previous answer.

READ ALSO  Top 3 Ways to Set Value of Textarea in JavaScript Dynamically

3. Using the nullish coalescing operator:

The nullish coalescing operator indicates (??) double question mark. This operator is new operator in JavaScript that checks if a variable is null or undefined. If the variable is null or undefined, it returns the second operand, otherwise, it returns the first operand. We have to use this nullish coalescing operator to check if a variable is defined by using it in an if statement. If the condition is true, the variable is defined and the if statement will execute. Here, the example:

let myVariable = 345;  // myVariable defined
if (myVariable ?? undefined !== undefined) {
  document.write(" myVariable is defined")
} else {
  document.write(" myVariable is not defined")
}

// Output: myVariable is defined

In this above example, we defined the varaible ‘myVariable’. So, the if statement condition is true, so we got the output “myVariable is defined”.

// myVariable is not defined
let myVariable;  
if (myVariable ?? undefined !== undefined) {
  document.write(" myVariable is defined")
} else {
  document.write(" myVariable is not defined")
}

// Output: myVariable is not defined

In this above example, we not defined the ‘myVariable’. So, the if statement condition is false and it execute else part. So we got the output “myVariable is not defined”.

Conclusion

These are some of the ways to check if a variable is defined in JavaScript and I recommend the ‘typeof’ operator.

Leave a Reply