Search code examples
javascriptarraysvariable-names

converting string to array name in JavaScript


my Goal is to be able to create a function that you can give a string as an argument, and be able to make an array that I could add Items to. You can see my attempt here, but it doesn't seem to work. aka, if I want to make a list name GroceryList, it returns GroceryList, but when I want to add an item to it, it says GroceryList is not defined.

function removeInstance(list, item){
  for(var i = 0; i < list.length; i++){
    if(item === list[i]){
      list.splice(i, 1);
      console.log(list);
      break;
    }
  }
}
function makeList(name){
  name = [];
  console.log(name);
  return name;
}
function removeAllItems(list, item){
  for(var i = 0; i < list.length; i++){
    if(item === list[i]){
      list.splice(i, 1);
      i--;
    }
  }
  console.log(list);
}
function addItem(list, item){
    list.push(item);
    console.log(list);
}

any help would be awesome. Thanks!


Solution

  • Parameters in JavaScript functions are passed by value, not reference; therefore, when you do something like this

    var foo = 'bar';
    
    function makeList(name){
      name = [];
      console.log(name);
      return name;
    }
    
    makeList(foo);
    console.log(foo); // shows 'bar'
    

    you are not modifying the variable which was declared outside the function. Changes to a parameter only affect that local function and not the original variable.

    At any rate, I cannot think of any possible scenario where you would need such a makeList function. If you need an array, just create one - there is no need for this!