Muirik Muirik - 4 years ago 106
Javascript Question

Building an Array Based on Passed-in Values

I'm working on a function where I check a value that is passed in, and then add it to an array. What I have isn't working, I just get an empty array:

let category = 'client';

function builtArray() {
let catArray = [];
if (category === 'client') {
catArray.push('client');
}
console.log(catArray);
}


What am I missing?

Answer Source

If I understand your question correctly,

let category = 'client';

function builtArray() {
  let catArray = [];
  if (category === 'client') {
    catArray.push('client');
  }
  console.log(catArray);
}

should be

let category = 'client';

function builtArray(cat) {
  let catArray = [];
  if (cat === 'client') {
    catArray.push(cat);
  }
  console.log(catArray); // => ['client']
}

builtArray(category);
  1. You have to "invoke" the function for it to run. This means calling it with (), that's what I've done at the end.

  2. You pass "category" in as an argument to the function, the function renames what you've passed in (as cat), it then checks to see if that variable is equal to the string client, if it is, it inserts it into catArray.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download