What strategies can be implemented to steer clear of utilizing global variables?

I have been advised against using global variables.

One of them is used to toggle client-side validation on and off.

The other two are used to control my drop-down menu.

If these shouldn't be global variables, where should I store them?

/* Global */

var enableValidation = 1,  // used to toggle client-side validation
    menuTimer = 0,
    menuElement = 0;
window.onload = initialize;

/*menu*/

function topMouseOver(id)
{
  resetMenu();
  if (menuElement) menuElement.style.visibility = 'hidden';
  menuElement = document.getElementById(id);
  menuElement.style.visibility = 'visible';
}
function internalTime()
{
  if (menuElement) menuElement.style.visibility = 'hidden';
}
function mouseOut()
{
  menuTimer = window.setTimeout(internalTime, 500);
}
function resetMenu()
{
  if (menuTimer)
  {
    window.clearTimeout(menuTimer);
    menuTimer = 0;
  }
}


Header 1  // This makes more sense
Content

Header 1  // Than this
Content

Answer №1

It seems like those variables could be suitable candidates for globals. Globals are typically reserved for tasks that impact the broader functionality of an application, such as controlling fundamental behaviors across multiple components.

If you'd like to create a "namespace" for them, you can do so easily:

var globalControls = {
    client_validation:1,
    menu_timer:0,
    menu_elment:0,
    window_onload:i0
};

Javascript currently doesn't have true namespaces. Objects serve as a workaround until a future version of ECMAScript potentially introduces this feature.

Answer №2

Check out this informative piece on the concept of javascript namespaces.

Answer №3

The topic at hand pertains to steering clear of global variables, although the title given is not quite accurate.

A way to accomplish this is by creating an object and setting properties within it. By doing so, the variables will be confined within the object's scope and won't clutter up the global scope.

For instance:

var settings = {
    enableNotifications: true,
    todoList: [],
    currentTask: '',
    someMethod: function () {
        // console.log(this.enableNotifications); //"this" refers to the object context
    }
};
// You can then access these properties like so:
console.log(settings.enableNotifications); // true

Answer №4

Utilizing namespacing effectively separates class definitions to avoid collisions, though it doesn't completely resolve the issue of global variables. It serves as a temporary solution.

To address global variables more comprehensively, one can employ a class instance that encapsulates properties which would otherwise be global. Encapsulation stands as a foundational concept in object-oriented programming.

For an illustration of a class with a namespace containing encapsulated properties, refer to the provided link. Moreover, a custom jQuery plugin utilizing this class is demonstrated.

In situations where persistent data traditionally necessitates a global variable, I opt for using http://api.jquery.com/jQuery.data/ to associate the data in object form to the DOM element and efficiently access it.

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

Is there a way to easily open the RSS link XML Element in a separate browser tab or window?

I have been exploring RSS and creating titles with links. However, when clicking on the link it opens in the same window. I would like it to open in a new window instead. Can someone please advise me on how to achieve this? <a href="http://www.google ...

The component fails to display on the page when using Vue-router

I'm having an issue with my router. I'm trying to display bodyComponent on my index page, but nothing is happening. I'm using laravel+vue. Can anyone point out where I might be going wrong? Here's my router: import Vue from 'vue& ...

Guide on including a JavaScript file in HTML during execution on Node.js

I have developed a basic nodeJs server with the following code in my server.js file: var http = require('http'); var fs = require('fs'); var path = require('path'); var server = http.createServer(function(req, resp){ // P ...

Tips for transferring information from a controller to a directive in AngularJS using AJAX requests

I want to pass data to a directive once the call is successful. Below is the ajax call from my controller: $scope.items ={ avatar: "" }; $scope.addComment = function(segment) { commentFactory.saveComment($scope.form.comment,segment,0, ...

Ways to retrieve information from a specific key

I'm currently facing a challenge accessing specific data objects that are referenced by keys. In this particular scenario, the "applicant" data is nested within an Event object. My goal is to extract this data and create a new object from it. While I ...

Vertical alignment of buttons in Cordova App Rate

Currently, I am utilizing phonegap along with the app rate plugin. When I execute the code: AppRate.promptForRating(true); All buttons are appearing in a singular line. Despite there being 3 buttons available, the text on the buttons is getting truncate ...

Parsing JSON data using a regular expression

Within my JavaScript file lies a plethora of object literals: // lots of irrelevant code oneParticularFunction({ key1: "string value", key2: 12345, key3: "strings which may contain ({ arbitrary characters })" }); // more irrelevant code My ta ...

Error in test runner: Cannot convert type 'Cucumber' to type '? extends Runner' in Java cucumber

I'm currently working on setting up the Cucumber framework using Java for running my tests, but encountering a type mismatch error in the Test Runner. package cucumbertest; import org.junit.runner.RunWith; import cucumber.api.CucumberOptions; import ...

Angular 6 is experiencing an issue with the functionality of the file toggle JS

Currently, I am utilizing the file toggle.js within the Urban theme. In the HTML chatbox, using the img, the file toggle.js is hardcoded and is functioning properly. However, when implementing code in Angular 6, the toggle.js is not functioning as expecte ...

Encode JavaScript field without affecting the appearance

I need to encode a specific search field before submitting it as a $_GET request. To do this, I am using the encodeURIComponent() function on that field before the form is submitted. $('#frmMainSearch').submit(function() { var field = $(this ...

What is the best way to identify a particular subtype of HTMLElement based on its tag name and then save that element within another one?

I have a function that generates a node and returns it. Here is an example implementation: addElement: function ({ parentNode, elementName, tagName, }) { // Creates and appends the new node. parentNode[elementName] = document.createEl ...

Requesting data download via AJAX for a CSV file

I have a unique feature on my website where users can customize and download a summary page based on specific elements they select to include in the final CSV file. To streamline the process, I want to display the summary page to the user and initiate the ...

What exactly are AngularJS module dependencies and how do they work together?

After exploring the tutorial example provided on AngularJs's site ( here) (The main HTML appears to be quite minimal with only ng-view and ng-app=phonecatApp included) Within the app.js file, we find: var phonecatApp = angular.module('phoneca ...

Transition property in CSS not functioning properly

In my webpage, I have div elements with multiple classes for easy manipulation in jQuery based on their nature. When I try to expand and collapse the div on a button click event, everything works fine except for the transition effect which is not working ...

Is there a way to restore a previous version of package-lock.json?

Currently, I am facing the challenge of adjusting a JS/node project that includes a package.json but lacks a committed package-lock.json file. Additionally, the original package-lock.json from the author is not available as newer versions have been develop ...

Searching for a specific value in a dropdown list during an iteration

Currently, I am iterating over an Ajax response to populate a JSON object in a select box. However, some of the JSON results may contain duplicate values. My goal is to check if a value already exists in the select box as I iterate through the loop. If a ...

Is it possible to retrieve the content that has been copied to a user's clipboard and then paste it into the console using javascript?

Is there a method to access and display the content that has been copied to a user's clipboard directly into the console using dev tools? ...

Handle clicking on a mesh

I'm currently working on implementing a click event for a mesh (cube) in order to perform some processing tasks. var cubeFor3D = new THREE.Mesh(new THREE.CubeGeometry(40,80,40),img3D); scene.add(cubeFor3D); // renderer.render(scene,c ...

Utilizing Angular and Cordova within a Virtual Directory

In an Angular application running in a virtual directory (https://{url}/{virtualDirectory}), I am attempting to encapsulate it within a Cordova application that references the same URL as the content source (<content src="https://{url}/{virtualDire ...

Implementing long polling for private messaging in PHP's chat functionality

Can you help me with a question I have regarding my chat form on the HTML page? Here is the code for the form: <form action="../addchat.php" method="POST" enctype="multipart/form-data"> <textarea id="textarea" style="border- ...