loading...

Javascript - dynamically generated variable names!

kpendic profile image Kresimir Pendic ・1 min read

Sometimes i feel like - put my hands up in the air .. no, sorry this post was not about songs and lyrics and putting your limbs airborne .. it's about my old issue that I thought I can't pull with javascript - but I was wrong. And that is, to generate some sort of 'loop-able' variable names - naming,, naming.. :(

Sort of, to be able to make variables in series, like: var1, var2, var3 ... simply by looping:

// some random arr
var arr = [ 2, 1, 4, 'cat', true, false, null ] ;
// loop and generate dynamic variable names
for( var i = 0; i < arr.length; i++){
    var var+i = i * i; // >> this will surely fail, can't do that in JS
}

But that is not doable in javascript.. and that got me pretty hard .. because my brain think in way that should be doable ..?

So today I found out that solution to that problem was instead of variables, to think of array members .. we can easily change keys in array, and as in this simple example below I'll be able to iterate over loop and add any key as variable name to it:

// some random arr
var arr = [ 2, 1, 4, 'cat', false ] ;
// foo array is "holder" of dynamic variables
var foo = [] ; 
// loop and generate dynamic variable names
for( var i = 0; i < arr.length; i++){
    foo[ "slider" + arr[ i ] ] = [ i ]
}
console.log( foo );
// [slider2: 2, slider1: 3, slider4: 0, slidercat: 1, sliderfalse: 6]

Posted on by:

kpendic profile

Kresimir Pendic

@kpendic

Hi, I'm simple man that likes to code and life in general. Optimistic by design :)

Discussion

markdown guide