Search code examples
javascriptsharepointreferenceerror

JavaScript variable seems to be treated as function


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


Solution

  • 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.