Eval for Variable Array Name Javascript

It's effective to use eval function to make variable array name. Let say the array name will be formed based on some logic or based on other variables. See the example below:

<script type="text/javascript">
   var prefix = 'abc';
   var abc_fruit = new Array('Apple','Orange','Mango','Berry'); 
</script>

Now if you try make the array name using the prefix like below then it will not work


alert(prefix + '_fruit'[0]); // This will throw an error;

But using eval method it can be easily done. Try the following

alert(eval(prefix + '_fruit')[0]); 

Comments