Skip to content Skip to sidebar Skip to footer

Way To Differentiate Between Declared Variable Vs Undeclared-2

Possible Duplicate Way to differentiate between declared variable vs undeclared I want to explain clearly my problem here. I have this condition. if(//condition1) var x1 = 1; els

Solution 1:

Use another variable to hold the information:

var which;
if (condition1) {
    var x1 = 1;
    which = 'x1';
} else if (condition2) {
    var x2 = 2;
    which = 'x2';
} else if (condition3) {
    var x3 = 3;
    which = 'x3';
}
console.log('Declared variable is: ' + which);

But remember, as explained in several answers in your earlier question, hoisting causes all the variables to be declared.

If you want to be able to use which to show the value of the variable, it would be better to use an object, with the name as the property:

var obj = {}, which;
var which;
if (condition1) {
    obj.x1 = 1;
    which = 'x1';
} else if (condition2) {
    obj.x2 = 2;
    which = 'x2';
} else if (condition3) {
    obj.x3 = 3;
    which = 'x3';
}
console.log('Declared variable is: ' + which + ' value is: ' + obj[which]);

Solution 2:

Why not use an Object?

var obj = {};
if(//conditon){
    obj.x1 = 1;
}
else if(//condition){
    obj.x2 = 2;
}

console.log(Object.keys(obj))

Note: this is the same logic that was given on the last v1 if this question


Solution 3:

You can use typeof

if(typeof x1 !== "undefined"){
// ...
}
// other checks

Solution 4:

You can iterate the context object by name. In global context its window, so you can iterate window and check
if(window[var_name] === undefined) Regarding your question, there`s one more way to cehck if variable was defined for any context - memoize all variables, then on every change to the context write new list of variables were defined. But it will require to keep list of variables defined for the context you need to track


Post a Comment for "Way To Differentiate Between Declared Variable Vs Undeclared-2"