Why Should we Use Exclamation Mark After Variable in JavaScript

JavaScript Exclamation Mark After Variable

Introduction

If you’ve ever come across JavaScript code with an exclamation mark after a variable. The exclamation mark in JS is also known as the negation operator and it is commonly used in JavaScript to invert a Boolean value. However, when used after a variable, it takes on a different meaning that can be confusing for beginners. In this article, we will explore what the exclamation mark after a variable means and how it can be used in JavaScript.

The exclamation mark after a variable

The exclamation mark after a variable is known as the “not-null assertion operator.” We can also used to tell the compiler that the variable is not null or undefined. This is useful when working with optional parameters or variables that might not have been initialized. We can prevent the compiler from throwing an error when it encounters a null or undefined value by using the exclamation mark.

For example,

let myVar;

if (!myVar) {
  console.log("myVar is null or undefined");
}

In this above example code:

  • We declared a variable ‘myVar’ without initializing it.
  • Then we use the negation operator to check if ‘myVar’ is null or undefined.
  • Since myVar is not initialized, it will be undefined, and the console will log “myVar is null or undefined.”

However, if we add an exclamation mark after myVar, like this:

let myVar!;

if (!myVar) {
 console.log("myVar is null or undefined");
}

The not-null assertion operator tells the compiler that ‘myVar’ is not null or undefined, even though it hasn’t been initialized. So, the console will not log “myVar is null or undefined.”

READ ALSO  Top 10 Important Event Listeners in Javascript

Conclusion

The exclamation mark after a variable in JavaScript is used to indicate that the variable is not null or undefined. We can use this method when working with optional parameters or uninitialized variables. It’s important to note that the not-null assertion operator should be used with caution, as it can lead to unexpected behavior if used incorrectly. Overall, understanding the meaning of the exclamation mark after a variable is an important aspect of mastering.

Leave a Reply