Categories
JavaScript Answers

How to define a variable if it doesn’t exist with JavaScript?

Spread the love

Sometimes, we want to define a variable if it doesn’t exist with JavaScript.

In this article, we’ll look at how to define a variable if it doesn’t exist with JavaScript.

How to define a variable if it doesn’t exist with JavaScript?

To define a variable if it doesn’t exist with JavaScript, we use the nullish coalescing operator.

For instance, we write

someVar = someVar ?? "Default Value";

to assign "Default Value" to someVar if someVar doesn’t exist.

The nullish coalescing operator is ??.

Conclusion

To define a variable if it doesn’t exist with JavaScript, we use the nullish coalescing operator.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *