0

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.

ScubaSteve
  • 7,724
  • 8
  • 52
  • 65
  • Unfortunately, I cannot. Mainly because the someVar1 is in another file and I believe sometimes the file isn't even loaded and that's why it's undefined. The question is mainly, why isn't the short-circuit catching the undefined? – ScubaSteve May 28 '20 at 13:13
  • @palaѕн I was able to simulate this and added gpouilloux's fix. https://jsfiddle.net/ScubaShneve/o6cL4asg/ – ScubaSteve May 28 '20 at 14:00
  • Ok, I have also linked a question as duplicate if you want to look into it. – palaѕн May 28 '20 at 14:11
  • It is very close, especially since the answer to this is one of the answers to the question that you linked. The difference I see is that I'm asking more why the short-circuit isn't catching it since undefined is falsy. The answer to my question explains that referencing the variable throws the error instead of undefined being checked in the short-circuit. – ScubaSteve May 28 '20 at 14:20

1 Answers1

1

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

frzsombor
  • 2,274
  • 1
  • 22
  • 40
gpouilloux
  • 26
  • 1
  • 3