Is there a way to verify the existence of a global function in JavaScript?

There is a global function that I have defined:

GlobalFunctions = {
      something: function() {

      }
};

I am aware of how to check if a function exists using:

if (typeof functionName == "function")

or the preferred method:

if (typeof functionName === "function")

However, even though the above methods work fine, when attempting to validate a global function, I encounter this error:

if (typeof GlobalFunctions.something == "function")

This results in the following error:

angular.js:12520 ReferenceError: GlobalFunctions is not defined
    at r.$scope.continueLogout (my-app.js:197)
    at b.$scope.logout (my-app.js:243)
    at fn (eval at compile (angular.js:13365), <anonymous>:4:209)
    at e (angular.js:23613)
    at b.$eval (angular.js:16052)
    at b.$apply (angular.js:16152)
    at HTMLAnchorElement.<anonymous> (angular.js:23618)
    at HTMLAnchorElement.dispatch (jquery.min.js:3)
    at HTMLAnchorElement.q.handle (jquery.min.js:3)

I tried searching on Google for solutions related to global functions, but found only solutions for regular functions.

Hope that explanation was clear, thank you.

Answer №1

When declaring the object, it appears that you are not utilizing the var, let, or const keywords.
It seems likely that your code is running with 'use strict'.

In the absence of strict mode, you have the ability to declare variables without using the var keyword, resulting in the variable being set on the global object:

Firstly, strict mode prevents accidental creation of global variables. In regular JavaScript, a typo in a variable assignment can create a new property on the global object and still function as intended.

With strict mode:

'use strict'
GlobalFunctions = {
      something: function() {

      }
};

if(GlobalFunctions) console.log('yeah');

Without strict mode:

GlobalFunctions = {
      something: function() {

      }
};

if(GlobalFunctions) console.log('yeah');

Answer №2

Solution uncovered:

if (GlobalFunctions !== undefined)

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Calculate the total width of all images

I'm on a mission to calculate the total width of all images. Despite my attempts to store image widths in an array for easy summing, I seem to be facing some challenges. It feels like there's a straightforward solution waiting to be discovered - ...

Managing and comparing category IDs in JavaScript to effectively store and render subcategories

My goal is to set the current category ID in a variable, and if the category changes, I want to store that as well. Then, I need to compare both IDs. If they are not equal, I want to set the subcategory to null. However, I am unsure of where my mistake lie ...

Issues with hemisphereLight and pointLight in three.js are causing them to not appear as expected

I recently started working with threejs and decided to follow a tutorial for creating a 3D portfolio. However, I'm facing an issue with the lighting in my scene. I suspect that it has something to do with the light source, but I am unsure about the va ...

Sneaky spam and ads embedded within Joomla template

Today, while examining the source code of a Joomla site I am developing, I stumbled upon some hidden links that seem to be spam. I have spent an hour searching through various template files but have been unable to locate them. The hidden links in questio ...

generate a customized synopsis for users without storing any data in the database

In order to provide a summary of the user's choices without saving them to the database, I want to display it in a modal that has already been created. Despite finding some sources online, none of them have worked for me so far. Below is my HTML: &l ...

"Unlocking the Power of mediaElementjs: Easy Steps to Accessing the Player Instance

I'm facing a small issue with the MediaElement.js player. To access the player instance, I usually use the following code (which works in HTML5 compatible browsers): // Retrieve player this.playerId = $('div#shotlist-player video').att ...

Assign the output of a function to a variable

I am trying to retrieve data from a function call in nodejs and assign it to a variable. The desired output should be "Calling From Glasgow to Euston", but I'm currently getting "Calling From undefined to undefined". Here is the code snippet: functi ...

Increase the Speed of setInterval in JavaScript

I'm currently experimenting with gradually decreasing the interval at which a function is executed within a setInterval method. Below is a simplified example code snippet: var speed = 100; window.setInterval( speed -= 0.01 , speed); I suspect that ...

Angular.js is a great tool for showing PDF files on a

I am facing a challenge while trying to incorporate a PDF file into my Angular.js website. The PDF is stored as a blob in a MySQL database and I want to display it as one of the partial views that appear on the main page when a link is clicked. Unfortuna ...

What is the process to incorporate the OR operator into a Mongoose schema?

I'm currently in the process of developing a website builder using Node.js, allowing users to incorporate various custom components to create their own websites However, I've encountered an issue with my mongoose model when attempting to designa ...

Tips for accessing a value from a setInterval function

Is it possible to retrieve a value from the setinterval function in JavaScript? $.ajax({ type : "POST", url:"<?php echo TESTMINE_APP_URL; ?>/ajax/export-details", data:'paginationHash='+paginationHash+'&exp ...

Ways to capture information from HTML with the help of JQuery

In the code snippet below, I am attempting to extract values from the h3 element and the data within the p elements. My goal is to have the extracted content in a format similar to this: NYC Row Restaurant Week From April 20st through April 28th Mother&a ...

concealing additional content within a DIV using ellipsis

Looking to conceal additional text within my DIV element with ellipsis (...) at the end Currently using: <div style="width:200px; height:2em; line-height:2em; overflow:hidden;" id="box"> this is text this is text this is text this is text </div ...

Ordering by does not effectively filter out numbers

I am using the ng-repeat directive in my code. <tr data-ng-repeat="list in vm.customer.lists | orderBy: list.id track by $index"> <td>[[list.name]]</td> <td>[[list.locations.length]] Location<span data-ng-cloak data-ng-i ...

Finding the difference between two arrays using nested loops

function filterArrayDifference(arr1, arr2) { let result = []; for (let i = 0; i < arr1.length; i++) { let isUnique = true; for (let j = 0; j < arr2.length; j++) { if (arr1[i] === arr2[j]) { isUnique ...

Is it possible to employ getBoundingClientRect() for several elements sharing the same class?

I'm in the process of implementing sticky navigation on my website that will dynamically change as users scroll through different sections. Specifically, when scrolling over a section marked with the class .dark, I want the logo and text color to swit ...

Ensuring numbers only with Svelte input validation, letters slip through my prevention efforts

I'm stumped on what is causing this issue. The input field is still displaying letters when it shouldn't be. <script> let value = ""; function isNumber(value) { return !isNaN(value); } function handle ...

There was an error in the <tspan> attribute dy: the expected length was not received, displaying as "NaN"

Encountering multiple errors while attempting to toggle the visibility of objects created in raphael. Specifically, I have a raphael-created house where clicking a button displays and animates a gauge; upon subsequent clicks, the house is shown and animate ...

What is causing the Uncaught TypeError when invoking a private JavaScript ES5 class?

My goal is to create a JavaScript class using ES5 syntax. However, I encountered an error when calling one method from another, which displays the following message in the console: Uncaught TypeError: root.abLog is not a function The relevant code snip ...

Use a spy to mock a component method using karma and jasmine

Encountering this error message during testing: ERROR: 'Error during cleanup of component' The issue stems from the following code snippet : ngOnDestroy(){ methodCallToMock() } To address this, I need to mock the methodCallToMock() functi ...