Which method of checking if a variable has been initialized is better/correct? (Assuming the variable could hold anything (string, int, object, function, etc.))
You can also use !!
before a variable to check if it's defined. E.g.
let dog = "woof";
let chineseCat; // Undefined.
console.log("1.");
console.log(!!dog && !!chineseCat ? "Both are defined" : "Both are NOT defined");
chineseCat= "mao"; // dog and chineseCat are now defined.
console.log("2.");
console.log(!!dog && !!chineseCat ? "Both are defined" : "Both are NOT defined");
Output:
1.
Both are NOT defined
2.
Both are defined