JavaScript "Variable Variables": How to Assign Variable Based on Another Variable

Javascript Variable Variables: how to assign variable based on another variable?

Looks like an array to me, or am I missing something?

var counters = [0,0,0];

function process(index) {
++counters[index];
/* or ++counters[index]+index, not sure what you want to do */
if (counters[index] === 13) {
/* do stuff */
}
}

How to define a variable with another variable value

Get the current date through Date(), padding to 2 digits, slicing last two, prepend with 'a' and eval.

var a270322 = "https://google.com" ;
var a280322 = "https://youtube.com" ;
var a290322 = "https://facebook.com" ;
var a300322 = "https://twitter.com" ;
var a310322 = "https://instagram.com" ;
var a010422 = "https://sgquizdaily.com" ;
var a020422 = "https://maps.google.com" ;
var a030422 = "https://gmail.com" ;

const now = new Date()
var day = ('0' + now.getDate()).slice(-2)
var month = ('0' +(now.getMonth() + 1).toString()).slice(-2)
var year = (now.getFullYear().toString()).slice(-2)
var Today = 'a'+ day + month + year
console.log(Today)

TodaysUrl = eval(Today)
console.log(TodaysUrl)

Using a variable to name another variable javascript

I'm going to guess that the eval fails because your serverID is a number (or a string that represents a number), so the statement would look like var 123 = {'server': 'test'}, which would give a syntax error.

In any case, a simple alternative would be to create a property on an object instead of a variable. Something like:

var myVariables = {};
//...
myVariables[serverID] = {'server': 'test'};

You could even add it to the global object, if it makes sense for your situation and you really need a global variable.

Setting a variable equal to another variable

The really short answer to both your questions is that when you make one variable equal to another, a COPY of what's in the first variable is made and stored in the second variable - there is no linkage between the two variables.

But, read on for more details and why it can seem like there is a link in some cases...


JavaScript, like many languages, divides data into two broad categories: value types and reference types. JavaScript value types are its primitives:

  • string
  • number
  • boolean
  • null
  • undefined
  • symbol

When you assign any of these types to a variable, the actual data is stored in that variable and if you set one variable equal to another, a copy (not a linkage) of the primitive is made and stored in the new variable:

var a = 10;  // Store the actual number 10 in the a variable
var b = a; // Store a COPY of the actual number stored in a (10) in the b variable
a = 50; // Change the actual data stored in a to 50 (no change to b here)
console.log("a is: " + a); // 50
console.log("b is: " + b); // 10

JavaScript OR (||) variable assignment explanation

See short-circuit evaluation for the explanation. It's a common way of implementing these operators; it is not unique to JavaScript.

How to set a variable by using another variable to name

Javascript variable depend on the lexical scope they are declared/defined in, wether it be a global scope or inside some function, if you're just defining your variable inside a the script tags, you might as well say

window[user_input_var] == true

which is equivalent to (in case user input was "red")

var red = true.

The most important part you should get out of this is variables in javascript are lexically scoped somewhere. Lexically scoped means physically declared somewhere, and based on that declaration we can use them in other places if we have access to this scope.

scopes can open up a lot of discussions here, and i don't think we need to dig down that rabbit whole. my example above should do the trick, if not determine in what scope/location you want your variable to be declared, and define there as in window.

var functionName = function() {} vs function functionName() {}

The difference is that functionOne is a function expression and so only defined when that line is reached, whereas functionTwo is a function declaration and is defined as soon as its surrounding function or script is executed (due to hoisting).

For example, a function expression:

// TypeError: functionOne is not a functionfunctionOne();
var functionOne = function() { console.log("Hello!");};

JavaScript check if variable exists (is defined/initialized)

The typeof operator will check if the variable is really undefined.

if (typeof variable === 'undefined') {
// variable is undefined
}

The typeof operator, unlike the other operators, doesn't throw a ReferenceError exception when used with an undeclared variable.

However, do note that typeof null will return "object". We have to be careful to avoid the mistake of initializing a variable to null. To be safe, this is what we could use instead:

if (typeof variable === 'undefined' || variable === null) {
// variable is undefined or null
}

For more info on using strict comparison === instead of simple equality ==, see:
Which equals operator (== vs ===) should be used in JavaScript comparisons?



Related Topics



Leave a reply



Submit