Stuff they don’t tell JavaScript noobs: Convert a string into a variable name

November 10th, 2011

Hey, I said this might turn into a series and it’s turned into a series of two! Last week, I put up a post about creating something you’d usually use jQuery to write using pure JavaScript. And as usual, I learned something I never expected to when I was writing my code. It turned out, I had no idea how to convert a string into a variable name. Of course, the answer turned out to simple, but it didn’t turn out to be the way I thought you would do it.

In my earlier post, I needed to see which link was clicked and then hide and display the colored divs based on that. Basically, if you clicked the blue link, then the page would only display the blue divs. I created a couple of arrays, blueDivs and redDivs and to make this work, I had to link the link with the id blue to the array blueDivs.

This is what I tried at first:

1
2
3
4
5
6
function showDivs(el) {
  var div = el + ‘Divs’;
  for (var i = 0; i < div.length; i++) {
    div[i].style.display = 'block';
  }
}

If I pass blue to the showDivs function, then blue plus Divs should give me blueDivs, right? Technically it does, but it’s a string and it’s not going to work because when the loop runs, it’s going to try to go through each character in the string. So this isn’t going to work for me. Why does this happen? Because JavaScript tries to guess what you want to do and any time you add anything to a string, the default result is to create a string. So if you were to write this:

1
2
var myNum = 1 + ' is a number!';
console.log(typeof(myNum));

Even though we’ve got a number in there, it will log out string as the type. So how do I change a string into a variable name? Well, a variable is really an object, so I need to convert our string into an object. How do I do this? Like this:

1
2
3
4
5
6
function showDivs(el) {
  var div = this[el + ‘Divs’];
  for (var i = 0; i < div.length; i++) {
    div[i].style.display = 'block';
  }
}

If you console.log(typeof(div)) on on this example, it will give you an answer of object. In fact, window[el + ‘Divs’] would do the same thing, in this case, I’m using this because it’s not a global variable. Now the variable div will equal blueDivs if I’ve passed blue to showDivs. And when the loop runs, then it will cycle through the blueDivs array.

Once again, this is one of those things that you probably won’t learn until you run into a situation that you need it.

Leave a Reply

Your email address will not be published. Required fields are marked *