Quick Index
Overview


There are cases where it's valuable to determine if a variable has been defined.

General Code



The code below will report true (defined).

If we comment-out the highlighted line, the variable prints false (not defined).
//const myGlobal = 10;

let isMyGlobalDefined = false;
try {
	myGlobal;
	isMyGlobalDefined  = true;
} catch(err) {
}

println(`is myGlobal defined: ${isMyGlobalDefined}`);



Solving Problem: Identifier has already been declared


Let's look at a specific problem.

Error: Identifier has already been declared
We have simplified the example shown. In reality, the highlighted lines would typically be in different files.

This code causes this error:

Identifier 'myGlobal' has already been declared

We'll next solve it with what we learned.
const myGlobal = 10;

const myGlobal = 10;

console.log(myGlobal);
Solution
We can eliminate the error as shown -- using try-catch block and only declaring if needed.

Another solution would be eliminating the redundancy. In some cases, that may be easier said than done. E.g., let's assume that the two files (containing the redunant declarations) may be used independently. In that case, each file would need to have the declaration.
const myGlobal = 10;
try { myGlobal; }
catch(err) {
	globalThis['myGlobal'] = 10;
}
console.log(myGlobal);
Solution (Function Case)
We can eliminate the error as shown -- using try-catch block and only declaring if needed.

Another solution would be eliminating the redundancy. In some cases, that may be easier said than done. E.g., let's assume that the two files (containing the redunant declarations) may be used independently. In that case, each file would need to have the declaration.

function myFunction() {
	return 'Hello from myFunction';

}
try { myFunction; }
catch(err) {
	globalThis['myFunction'] =
		function() {
			return 'Hello from myFunction (from catch block)';
		};
}

println(myFunction());