Is it acceptable to use "string" as a variable name in JavaScript?

Any tips on getting the code below to function properly?

var x = 'name';

After that, I want to utilize the value inside x like a variable and assign it so that when I call for NAME, I get this outcome:

var name = 'NAME';

Can this be achieved?

Answer №1

Indirectly, yes. You cannot directly assign to the global scope in JavaScript. However, you can assign to window, which effectively creates a globally accessible variable:

var key = 'xyz';
window[key] = 'example';
alert(xyz);

Alternatively, a more recommended approach is to create your own object for better control:

var key = 'xyz';
var custom_object = {};
custom_object[key] = 'example';
alert(custom_object[key]);

Answer №2

Instead of relying on the window object, utilizing an object might be a more efficient approach.

let info = {name: "John"};
let key = "name";
info[key]; //=> John

let newKey = "age";
info[newKey] = 30;
info["age"]; //=> 30

This method appears to be neater and self-sufficient compared to the usage of the window object.

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

What is the method to retrieve content from a different domain using .load()?

When I try to retrieve data from a different domain using .load() or other jQuery ajax functions, it doesn't seem to work. However, accessing URLs on my own domain works perfectly fine. I've heard about a workaround involving PHP and setting up ...

Retrieving a time series data set from a JSON stream

Even though ThingSpeak offers great charts, I'm interested in retrieving data from ThingSpeak and creating my own visualizations using Google Charts. When extracting a "feed" from ThingSpeak, the data is presented in a JSON object like the one below: ...

Exploring Javascript parameters with the power of jquery

Is it possible to pass a parameter from PHP into a JavaScript function within HTML? I am currently facing an issue where my code crashes when it reaches a certain condition. This is the code snippet causing the problem: $str="<input type='submit&a ...

Interactive Bar chart updates in real-time with Highcharts and AngularJs

With the help of a sample from Highcharts (here), I successfully integrated a bar chart into AngularJs. Below is the HTML code: <!DOCTYPE html> <html ng-lang="en" ng-app="myModule"> <head> <meta charset="ISO-8859-1"> <script sr ...

Images copied using Gulp are often distorted or incomplete

There is a simple task of moving an image from one folder to another. gulp.task('default', function () { return gulp.src('./img/*.*') .pipe(gulp.dest('./image')); }); Previously, everything was running smoothly, b ...

After clicking a button in AngularJS, how can you retrieve one of the two JSON files and store it in a $scope variable?

For instance, You have two JSON files: Json file #1: [{colorname:blue},{colorname:blue}] Json file #2: [{colorname:red},{colorname:red}] Within the controller, there exists a variable called $scope.color In the HTML code, there are two buttons named " ...

Building an Express API using ES6 script: A Step-by-Step Guide

After creating a no-view REST API using the express generator, I decided to convert everything to ES6 script and compile it with Babel. However, upon entering localhost after the changes, an error message appeared: No default engine was specified and no ...

Is it possible to dynamically add plotLines to the xAxis using datetime in HighCharts?

Hey there! I've been playing around with adding plotlines in Highcharts and I'm loving it. It's really easy to define a date time on the xAxis for a plotline, like this: xAxis: { plotLines: [{ color: '#dadada', ...

What is the process for executing JavaScript code that is stored as a string?

After making an AJAX call, I receive a random string (constructed dynamically on the server) that contains JavaScript code like: Plugins.add('test', function() { return { html: '<div>test</div&g ...

The utilization of count variable is not permitted in embedded array lookup

I've been using C# for quite some time, but I'm facing a challenge with a basic concept in the JavaScript part of my project. The following code snippet is part of a larger function I've written: addPaymentsToBreakdown = function () { f ...

Executing a function a specific number of times in Jquery

I have a query regarding JQuery related to randomly placing divs on a webpage. The issue I'm facing is that it currently does this indefinitely. Is there a way to make it run for a specific duration and then stop? $(document).ready(function () { ...

Challenges in retrieving information from a two-dimensional JSON dataset

I am encountering an issue with a nested JSON structure. JSON: [{"id":"15", "rand_key":"", "landlord_name":"Shah", "property_req_1":{ "lead_req_id":"", "lead_id":"0", "category_id":"1", "region_id":"1", "area_location_id":"17", ...

Alert: Prop type error encountered - The prop 'open' must be defined in Snackbar component

Recently, I've been implementing jest snapshot tests into my application. The main focus is on the LoginForm component. render() { return ( ... <DynamicSnack dialogOpen={this.props.dialogOpen} snackOpen={this.props.sna ...

React Ant Design: Toggle Visibility of Columns

Seeking a method to toggle the visibility of columns for the Table Component in Ant Design. The goal is to include a checkbox next to each column name. When unchecked, the column should be hidden. In my previous experience with react-table, accomplishing ...

Is it possible to nest v-for directives within a component file?

Even after going through the VueJS tutorials multiple times, I am still unable to find a solution to this problem. My issue revolves around displaying a list of lists using accordions, which is supposed to work smoothly with vue-strap components. For exa ...

Ensuring the accuracy of nested objects through class validator in combination with nestjs

I'm currently facing an issue with validating nested objects using class-validator and NestJS. I attempted to follow this thread, where I utilized the @Type decorator from class-transform but unfortunately, it did not work as expected. Here is my setu ...

I must develop a custom function that generates a pure JavaScript string with the 'name' index and includes all the 'props'

My code is almost correct, but instead of returning a ':' in the Json result as desired, it returns a ','. Is there a way to achieve the desired result without modifying the JSON string like I did with the "replaces"? I am searching fo ...

I've been encountering a recurring issue of receiving NaN followed by a number in React. Any suggestions on how to resolve

click here to see the image const number = parseInt(props.detail.price,10) const toLocale = number.toLocaleString("ko-KR") console.log(toLocale) return ( <div> <Descriptions title="Product ...

The functionality of the onclick button input is not functioning properly in the Google

Here is some JavaScript code: function doClick() { alert("clicked"); } Now, take a look at this HTML code: <div > <table border="2" cellspacing="0" cellpadding="0" class="TextFG" style="font-family:Arial; font-size:10pt;"> <tr> <t ...

Customize the appearance of the Vue.js datepicker starting from today's date

I am currently using the vue-datepicker component to display a date input field in my form. I want to set the default date to the current day and disable the selection of past dates. Additionally, I need to change the language of the component but it seems ...