Deep Tech Point
first stop in your tech adventure
How to define variable if it doesn’t exists in Javascript?
November 17, 2021 | Javascript

This is simple question and may sound like the answer is also simple. However, there are few things you need to take into account when creating variables and assigning values just to be sure you’re not overwriting existing variables. It’s even more important in complex projects with multiple modules because it’s sometimes hard to keep track of each variable and their scope.

For global variables we can write something like this:

var someVar = window.someVar || 'Not defined, set this as a value';

It’s good rule of thumb to check if variable already exists in window namespace because global variables are assigned to window object as it’s property, but it is perfectly fine if you write:

var someVar = someVar || 'Not defined, set this as a value';

In some situations this might be problematic solution because someVar can be a falsy value. Values like ”, false, and 0 would evaluate first part of expression as false and set the default for someVar. If you want to be able to assign falsy value to someVar you should write something like this:

if (typeof someVar === 'undefined') {
    // var someVar = 'Not defined, set this as a value';
}

You can also use ternary operator to do the same thing but in shorter form, like this:

someVar = typeof(someVar) === 'undefined' ? 'Not defined, set this as a value' : someVar;

As a beginner you won’t be too concerned about the way of defining variables, but as your initial projects progress to more complex solutions at some point you might ask yourself why your code isn’t working the way you are expecting. Variable overwriting can be source of hard-to-find bugs because your code could work in 99% of situations but then fail in some edge cases.