Divya MV Divya MV - 2 months ago 10
Javascript Question

angular.isDefined vs typeof

This question is specific to angular.isDefined() being named isDefined Don't we expect it to find a way to return false if the variable passed to it is not defined rather than throwing an uncaught error. I am looking for an angular equivalent of typeof operator to detect the not Defined variables.In the below example

x
is not Defined and
typeof x
doesn't throw any
Uncaught ReferenceError: x is not defined
error.where in if i had used
angular.isDefined
i would have received a
not defined error
.

if(typeof x != 'undefined')
alert("defined");
else
alert("undefined);


angular.isDefined(x) throws
Uncaught ReferenceError: x is not defined
if x is not Defined .

if(angular.isDefined(x)) // throws error because x is not defined
alert("defined");
else
alert("undefined);





var x;
if(angular.isDefined(x)) // does not throw error as x is defined though not **initialiased**
alert("defined");
else
alert("undefined);


Is there an angular alternative to
typeof x !='undefined'
.Let me explain how am i ending up with this scenario.I have
createContext()
function in a js file which i am not allowed to modify.and this function defines
context="something useful"
and i have two controllers
commonController
and
contextController
.
commonController
is executed first and registers for an custom eventhandler which needs access to
context
.then
commonController
executes which calls
createContext()
.sometimes depending on the execution time even before the
createContext()
is called.the eventHadler is triggered and would try to access the variable which is not yet defined. I can not call
createContext()
anywhere else other than in
contextController
.

Answer

As you have now clarified in the comments in @squiroid's answer, your canvasDesign function looks like this:

canvasDesign = function() { 
    var canvas1 = document.getElementById("canvas1"); 
    if(canvas1 != null) context1 = canvas1.getContext('2d');
}

That function is creating an implicit global variable (because it's not using var on context1).

That is a bad practice, which is forbidden in ES5 strict mode, and the correct thing to do is to fix the code to stop using antipractices. If that is not an option, your best bet is to continue to use typeof context1 === 'undefined'. As this question clarifies, it's impossible to create a general function to check for the existence of a variable.

Two other options:

  • Use angular.isDefined(window.context1). This will allow you to check for a global variable without throwing an error, but this approach will break if at some point the variable is made non-global.
  • Put var context1; at the top of your file, outside any functions. This will ensure that the variable is at least declared, and allow you to call angular.isDefined(context1) safely.