javascriptundefinedshort-circuit-evaluation

JavaScript Short-Circuit Still Throws Undefined Error


I'm working with some older code in AngularJs. There's a variable someVar1 that could possibly exist in the JS ether and if it does, I wanted to attach it to my scope like so:

$scope.someVar2 = someVar1 || 0;

But occasionally, when someVar1 doesn't exist in the ether, I get this error:

Error: someVar1 is not defined

It points directly to the line and column of someVar1 in the JS file.

Why is this happening? I was under the impression that someVar1 || 0 would check if someVar1 was undefined, which is falsy, and set the $scope.someVar2 to 0.


Solution

  • To have someVar1 being potentially undefined, this variable must be declared first.

    In your case, it is possible that the code in charge of defining someVar1 is called after this script (or maybe never).

    I'd suggest checking this in the first place.

    As a hack, you could check if the variable is defined yourself by using typeof.

    typeof will not throw a ReferenceError is the variable is not defined but instead will reply undefined if the variable is not defined or have undefined value.

    For example, your code can look like this:

    $scope.someVar2 = typeof(someVar1) !== "undefined" ? someVar1 : 0;
    

    Reference: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Errors/Not_defined