How to declare a var with a customized name in js? - javascript

I would like to declare a variable whose name is the content of another other variable. It is possible ?
I tried this :
var "x" + "y" = 1;
to declare this :
var xy = 1;
But this throw an error : Uncaught SyntaxError: Unexpected string

The only way (AFAIK) to create local variables with dynamic names is with eval(). This is not a great solution, because of performance concerns. You can also create global variables with dynamic names using the global object.
eval(`var ${varName} = 123;`);
globalThis[varName] = 123;
However, creating variables with dynamic names is not a common practice. Most likely what you need is a Map.
const varName = "varName", otherVarName = "otherVarName";
const map = new Map();
map.set(varName, 123);
map.set(otherVarName, 456);
console.log(map.get(varName), map.get(otherVarName));

In JavaScript somehow you can create dynamic variables using eval function or window object:
eval('var xy="evalTest";');
alert(xy);
window["xy"] = "windowTest";
alert(window["xy"]);

Another possible solution is to create a json with all your global variables.
//create an empty json (at the top of your javascript file)
const globalVariables = {};
//add variable and value to your json
globalVariables["x"+"y"] = 1;
//access value from json
console.log(globalVariables["xy"]); // this function will log 1 to the console

Related

How to call Array name with a string in JS

const EleList = [1,2,3]
name = 'Ele'
const render = function(type){
window[type + 'List'].forEach(function(value){
console.log("LOL")
render('Ele')
What am i supposed to replace the window[name + 'List'] with to call an array using strings.
const or let variables are not added to the global window object.
Replacing const with var should solve your problem.
var EleList = [1,2,3]
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/const
Global constants do not become properties of the window object, unlike var variables.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/let
Just like const the let does not create properties of the window object when declared globally (in the top-most scope).

How to create dynamic variables using jquery?

I want some jquery variables to be created dynamically. In my code I am having a loop, and with the loop values I want to create some variables. Here is my sample code.
array=["student","parent","employee"]
$.each(user_types, function( index, value ){
var value+"_type" // this is the type of variable i want to build.
})
I have found about eval function. That code goes like this.
var type = "type"
eval("var pre_"+type+"= 'The value of dynamic variable, val';");
alert(pre_type) // this gives 'The value of dynamic variable, val' in alert box.
Is there any alternate ways as I have read the eval function is not prefered while coding .js files.
Any time you find yourself using a variable in the name of a variable, you probably want to use an object literal. Create the object with curly braces {}, and then set the object property key using square bracket notation:
var user_types = ["student","parent","employee"];
var types = {};
$.each(user_types, function( index, value ){
types[value] = 'The value of dynamic variable, val';
});
JSFiddle
Note: You haven't tagged it, but I assume because you've used each() that you are using jQuery, please correct me if I'm wrong.
First of all i must say that i can't think of any reason why you want to do this.
If you really need to have those variables, in global scope, you can do the following:
var array=["student","parent","employee"]
array.forEach(function(value){
window[value+"_type"] = 'My value ' + value;
});
console.log(student_type);
console.log(parent_type);
console.log(employee_type);
If you don't want the variables in global scope, i'm afraid i don't know an elegant solution.
I used array.forEach instead of your jQuery loop because the problem is not related to jQuery at all and because i don't think you said enough of your logic to make a coherent example.
EDIT: I should make it clear that while the 'variables' created behave mostly like other variables in global scope, they are NOT variables. Here is how they differ:
// Difference 1: hoisting
console.log(x); // undefined
console.log(y); // ReferenceError: y is not defined
var x = 5;
window[y] = 5;
console.log(x); // 5
console.log(y); // 5
// Difference 2: [[Configurable]]
delete x;
delete y;
console.log(x); // 5
console.log(y); // ReferenceError: y is not defined
If you want to add an intermediate variable inside the string, you can do it as follows:
var itemSelect: number = 1;
$(`#tab${this.itemSelect}-tab`).tab('show');
/* Result -> $(`#tab1-tab`).tab('show'); */
/* HTML */
<a id="tb1-tab"> </a>

how to reference object as string name

I need to reference my object as a string but I am having issues.
ideally I would like this to work ['mystring'].myproperty; but obviously this wont work.
Is there another way besides the options below?
// auto generated ecample/////////////
var mystring = {
myproperty :'test'
}
/////////////////////////////////////
var optionA =mystring.myproperty; // works
var optionB = window['mystring'].myproperty; //gives issues
var optionC = eval('mystring').myproperty; //gives issues
var optionD = ['mystring'].myproperty; // wont work
If your variables are defined on a global scope, the following works
window[ mystring.myproperty ].data
If you are in a function's scope, things get a lot harder. Easiest way then is to define your objects in a specific namespace on window and retrieve the objects similar to the above code.

Javascript: Naming arrays programmatically

Is it possible to create a new Array, giving it the name of the content of a variable?
For example something like this:
var nameofarray = "array_name";
var ¿nameofarray? = new Array();
So that ¿nameofarray? gets the value of "array_name"?
Assuming you are in global scope (called window) so:
var nameofarray = "array_name";
window[nameofarray] = new Array();
Otherwise it's only posible on objects:
function a() {
var nameofarray = "array_name";
var obj = {};
obj[nameofarray] = new Array();
}
You can also use eval. Which is used for evaluating a string to JavaScript code:
eval('var '+ nameofarray+'=new Array()');
This will work in local scopes as well, but I hardly ever recorment it to anyone.
You would maybe like to read: http://javascriptweblog.wordpress.com/2010/04/19/how-evil-is-eval/
In PHP and other languages, they are called variable variables. This might help: Javascript "Variable Variables": how to assign variable based on another variable?
If nameofarray is declared in the global scope, you can use the window object:
window[nameofarray] = []; // Use an array literal instead also
^^^^^^^^^^^^^^^^^^^
But you really shouldn't be doing this.

Javascript create variable from its name

In PHP we can do this:
$variable = "name_of_variable";
$this->{$variable} = "somevalue";
how to do this in javascript?
where use case should look like:
function Apple(){
var name = "variable_name";
this.(name) = "value";
}
console.log(new Apple());
to output
[Apple: {variable_name:"value"}]
try:
this[name] = "value";
All objects can use dot and array notation for variable access.
Also note, this will allow you to create name value pairs that are inaccessible via dot notation:
var foo = {};
foo['bar-baz'] = 'fizzbuzz';
alert(foo.bar-baz); //this will not work because `-` is subtraction
alert(foo['bar-baz']); //this will work fine
If you are creating a new object literal, you can use string literals for the names for values with special characters:
var foo = {'bar-baz':'fizzbuzz'};
But you will not be able to use variables as the key within an object literal because they are interpreted as the name to use:
var foo = 'fizz';
var bar = { foo:'buzz' }
alert( bar.fizz ); //this will not work because `foo` was the key provided
alert( bar.foo ); //alerts 'buzz'
Because other answerers are mentioning eval, I will explain a case where eval could be useful.
Warning! Code using eval is evil, proceed with caution.
If you need to use a variable with a dynamic name, and that variable does not exist on another object.
It's important to know that calling var foo in the global context attaches the new variable to the global object (typically window). In a closure, however, the variable created by var foo exists only within the context of the closure, and is not attached to any particular object.
If you need a dynamic variable name within a closure it is better to use a container object:
var container = {};
container[foo] = 'bar';
So with that all being said, if a dynamic variable name is required and a container object is not able to be used, eval can be used to create/access/modify a dynamic variable name.
var evalString = ['var', variableName, '=', String.quote(variableValue), ';'].join(' ')
eval( evalString );
You can use square bracket notation in Javascript:
variable = "name_of_variable";
window[variable] = "somevalue";
You can do this with any object in Javascript.
var name = "var_name";
var obj = {};
obj[name] = 'value';
alert(obj.var_name);
I suggest using associative arrays to do whatever you're trying to do as they are significantly cleaner and easier to debug.
However if you really insist, you can use eval() to accomplish this:
variable = "name_of_variable";
eval(variable + " = \"somevalue\""); // this will work, but please do not do it
alert(name_of_variable);
EDIT: It his just come to my attention that a significantly easier (and better) way of doing this is by simply accessing the window object:
window[variable] = "somevalue";
http://jsfiddle.net/WJCrB/
window['name_of_variable'] = 'somevalue';
or
eval('var ' + variable_name + ' = ' + variable_name + ';');
Beyond that, don't do this. Variable variables are NEVER a good idea and make it nearly impossible to debug problems when (invariably) things break.

Categories

Resources