JavaScript Dynamic Variable Names

You can only do that with bracket notation, which means you have to attach the variables to something.
The global scope would be window, so that would be window['hello' + newCount], but polluting the global namespace with a bunch of random properties doesn’t sound like a good idea, so using an object seems better

var vars = {};
var newCount = parseInt($('#hello').html(), 10);

$('.hello').click(function(){
    newCount++;
    vars['hello' + newCount] = '<p>Hello World</p>';
}); 

alert( vars['hello1'] );

FIDDLE

Leave a Comment