0

I'm developing some JavaScript that will sit on a SharePoint page. SharePoint provides a global function getCurrentCtx(). Unfortunately this function is only available on certain pages. My JavaScript needs to test to see if this function exists.

Easy, right?

if(getCurrentCtx) {
    //Code here
}

Not so fast:

Uncaught ReferenceError: getCurrentCtx is not defined

WTF? If it's not defined, it should be undefined which is falsey and so the if statement should simply be skipped.

console.log(getCurrentCtx)

Uncaught ReferenceError: getCurrentCtx is not defined

As far as I know, the uncaught referencerror exception occurs when you try to call a function that doesn't exist. So why am I getting it when I'm just trying to retrieve the value of a variable?

Thanks,

YM

Joshua Walsh
  • 1,915
  • 5
  • 25
  • 50

2 Answers2

3

As far as I know, the uncaught referencerror exception occurs when you try to call a function that doesn't exist.

Incorrect.

If you are trying read the value of any variable (or more general, binding) that doesn't exist (e.g. no var getCurrentCtx anywhere), then JS throws a reference error.

Relevant part in the specification.

Exception: typeof getCurrentCtx would return "undefined", because it tests whether the variable (reference) is resolvable (exists) before it reads it.

Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
1

Variables that are not declared throw the Uncaught ReferenceError exception. Undefined properties return undefined. Something like this will probably work.

if(typeof getCurrentCtx !== "undefined") {
    //Code here
}

Alternately, the following might also work.

if(self.getCurrentCtx) {
    //Code here
}

Both of these are untested on Sharepoint, but would work in plain JavaScript.

Alexander O'Mara
  • 58,688
  • 18
  • 163
  • 171
  • I'm giving this one the green tick because it mentons the distinction between variables and properties. Attempting to access the variable as a property of the window object is easier for me than doing a typeof. – Joshua Walsh Aug 05 '14 at 23:44