2

When commenting out the anonymous function expression "a" below, how do you properly check for NULL on "b"? Use case: Lets say "a" is an in-page JS include (library) that is assigned to "b", but the library failed to load and now we have a console error.

var a = function () { return 'Success!'; } // Exclude this line
var b = a();
if (typeof b !== 'undefined' || b !== null) { // These checks do not work.
   console.log(b);
} else {
   console.log('Failed!');
}
Cody Tolene
  • 127
  • 1
  • 1
  • 10
  • 3
    If you remove `a` function you'll get referenceError on `a` – YouneL Dec 29 '17 at 22:31
  • Yeah, what @YouneL said - the check *works*, the problem is that the code fails before getting there. – VLAZ Dec 29 '17 at 22:35
  • 1
    Have you tried: `var b = typeof a !== 'undefined' ? a() : undefined` or more specifically: `var b = typeof a == 'function' ? a() : undefined` Then you can just check: `if (typeof b !== 'undefined') {/*...*/}` – Mark Dec 29 '17 at 22:35
  • 1
    @Mark_M or `try...catch` which is designed for situations like that. Then again, if `a` wasn't loaded, I don't think error handling is really the way to go but finding the root reason and removing it. – VLAZ Dec 29 '17 at 22:41
  • @vlaz yes, I agree. – Mark Dec 29 '17 at 22:46

1 Answers1

1

If i understand your use case correctly, this line of code is in your side of the app:

var b = a();

If that is correct, you can re-assign a conditionally with itself or with a new function or an object.
This is a common pattern when you want to check if a global variable exists.

Here is a running example when a is not exists:

// library 
//var a = function () { return 'Success!'; } // Exclude this line

// my app
var a = a || function(){};
var b = a();
if (b) {
   console.log(b);
} else {
   console.log('Failed!');
}

And here is the same code when a exists:

// library 
var a = function () { return 'Success!'; } // Exclude this line

// my app
var a = a || function(){};
var b = a();
if (b) {
   console.log(b);
} else {
   console.log('Failed!');
}
Sagiv b.g
  • 30,379
  • 9
  • 68
  • 99