Populating another array from array – Javascript

Your code isn’t working because you are not initializing bar:

var bar = [];

You also forgot to declare your i variable, which can be problematic, for example if the code is inside a function, i will end up being a global variable (always use var :).

But, you can avoid the loop, simply by using the slice method to create a copy of your first array:

var arr = ["apple","banana","canaple"];
var bar = arr.slice();

Leave a Comment