Determining if a variable has been defined in JavaScript

In my JavaScript code, I declare global variables named with the prefix "sld_label" where "label" can be any string. These variables are initialized as objects that contain a function called setval. Now, I have a function that receives a label in a string parameter called qq and I need to determine if the corresponding sld_label variable has been defined. How can I achieve this without causing an error?

Currently, I am using the following code snippet (which works but triggers an error in Firebug):-

function setclrques(qq, op)
{
  if (typeof(eval('sld_'+qq))=='object') eval('sld_'+qq+'.setval('+op+')');
}

Any assistance would be greatly appreciated!

Answer №1

In the case that it is global, it will become a member of window, allowing the code below to function correctly:

if (typeof window['sld_' + qq] == 'undefined') alert('sld_' + qq + ' is not defined.');

Answer №2

I recently developed a similar solution to this problem.

function Example()
{
}

Example.prototype.updateValue = function(options)
{
    alert(options);
}

function setQuestionColor(question, option)
{
    var object = window['sld_'+question];
    if( object!=undefined && object.updateValue!=undefined )
    {
        object.updateValue(option);
    }
}

var sld_qwer = new Example();
setQuestionColor("qwer","test!");

However, I would suggest considering using an associative array instead of individual variables for storing objects:

function Example()
{
}

Example.prototype.updateValue = function(options)
{
    alert(options);
}

var sld = [];
sld["qwer"] = new Example();

function setQuestionColor(question, option)
{
    var obj = sld[question];
    if( obj!=undefined && obj.updateValue!=undefined )
    {
        obj.updateValue(option);
    }
}

setQuestionColor("qwer","test!");

Answer №3

Check if the value of "sld_" + qq is an object, then assign the value of op to it.

Answer №4

To determine if a variable exists:

if (typeof myVariable != 'undefined') // Can be used in any scope
if (window['variableName'] != undefined) // Works in global scope
if (window['variableName'] != void 0) // Compatible with older browsers

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

Update the value of the following element

In the table, each row has three text fields. <tr> <td><input type="text" data-type="number" name="qty[]" /></td> <td><input type="text" data-type="number" name="ucost[]" /></td> <td><input ty ...

Is there a way to horizontally center Material UI Switch and its icon props?

I'm using Material-UI to implement a Switch component on my project. This particular component allows for the addition of icons, however, I've encountered an issue with alignment when including them. Is there a way to horizontally center align b ...

Encountering the "v_isRef": true flag while utilizing Vuex within a composition function

I encountered an unexpected outcome when using the loginString() function in my template. It seems that there is a need to include .value in templates, which I thought wasn't necessary. { "_dirty": true, "__v_isRef": true, "__v_isReadonly": true } ...

Tips for retrieving a selected date from an HTML textbox labeled as "Date"

My goal was to find the differences between two dates by utilizing an HTML Date textbox. <input type="text" name="datein" id="datein" value="" class="inputtexbox datepicker" style="display: none" is-Date/> <input type="text" name="dateto" id=" ...

Calculating the mean value of a multidimensional array that has been sorted in JavaScript

Check out the structure of my JSON File below. { "questions": ["Question1", "Question2"], "orgs": ["Org1", "Org2", "Org3"], "dates": ["Q1", "Q2", "Q3"], "values": [ [ [5, 88, 18], [50, 83, 10], ...

I'm curious to know why my jQuery function fadeOut is functioning properly while slice isn't working as expected

I'm trying to create a button that displays three consecutive posts After clicking on "view all", the three "div" elements should become visible I'm attempting to use jQuery to make the three 'div' elements appear when the view all bu ...

Pause jQuery at the conclusion and head back to the beginning

As a beginner in the world of jQuery, I am eager to create a slider for my website. My goal is to design a slideshow that can loop infinitely with simplicity. Should I manually count the number of <li> elements or images, calculate their width, and ...

Ways to specify the specific option within a select field

Here is my question: <select name="currency" id="currency"> <option value="AUD"&lgt;AUD</option> <option value="BDT"&lgt;BDT</option> <option value="EUR"&lgt;EUR</option> & ...

"Discover the Step-by-Step Guide to Launching Fresh Content or Code in the Current Tab and

I have a webpage with multiple tabs, each representing different content. Now, I want to create a functionality where if a user clicks on the "Home" tab, they are prompted to enter a password (e.g., 1234). Upon entering the correct password, the user shoul ...

Having difficulty incorporating an input value into an Angular function

For a school project, I am creating a login form using Angular. Below is the HTML code: <input type="text" ng-model="username" name="username" /> <input type="text" ng-model="password" name="password" /> <button (click)="submit(username, pa ...

When attempting to print using React, inline styles may not be effective

<div styleName="item" key={index} style={{ backgroundColor: color[index] }}> The hex color code stored in color[index] displays correctly in web browsers, but fails to work in print preview mode. Substituting 'blue' for color[index] succe ...

Troubleshooting: Issue with jQuery not retrieving the value of input:nth-child(n)

My goal is to dynamically change the price when the model number changes, requiring the id number and quantity to calculate it accurately. Here is the HTML code I have: <div class="col-sm-9 topnav"> <span> ...

Can Ajax be utilized to call a PHP script that contains another Ajax function?

I have set up a checkbox that triggers an Ajax call to another PHP script once checked. In this PHP script, there are three text boxes and a button. When the button is pressed, another Ajax call is made to execute yet another PHP script, all within the sam ...

function that contains a MySQL assignment

My history table includes a DATETIME column. Can I assign a variable inside a DATEDIFF function? Here is the query in question: SET @LASTDATETIME='2000-01-01 00:00:00'; SELECT DATETIME, @LASTDATETIME, TIMEDIFF(DATETIME, @LASTDATETIME:=DATETIME) ...

A step-by-step guide on disabling Google Analytics in a Next.js document.js file

Upon a user's initial visit to the website, they are presented with the option to either accept or decline tracking cookies. If the user declines, a cookie is set with the value of false. I am in need of a way to conditionally run the gtag script base ...

Scrolling through image galleries with automatic thumbnails

I am looking to create an automatic image scrolling feature on my webpage using a bunch of images I have. I have searched for a solution but have not found one that fits my requirements. I don't think a carousel is the right approach for this. The sol ...

The error message "THREE is not defined" indicates a problem

Hey there! I've been experimenting with running some three.js examples on my local machine. I ran into some security issues, so I set up a local server using Python. While the background image and text appear as expected, the animations are not workin ...

Ajax is unintentionally duplicating the request

When the "async" parameter is set to "true", ajax sends two requests at the same time. But, when it is set to "false", there are no issues. To prevent the page from reloading, I am using the following code: $(document).ready(function() { $(document).on(& ...

Assigning controller variables within an ajax request

I'm new to AngularJS and I have a question about controller attributes. I've created an attribute called 'anuncio', which contains an array of objects as shown below: var anuncioModule = angular.module('anuncioModule',[]); a ...

Adjust parent div size based on image size increase

I am currently facing a situation where I have a page displaying an image, but sometimes it appears too small. In order to make the image larger, I have utilized CSS Transform and it is working well. However, the issue lies in the fact that the parent DIV ...