0

I set up an empty array, then I'm doing a "for loop" where I set up an empty object, add things to the empty object and finally push the object onto an array.

Technically the array in the beginning should be empty but when I console log it, it still has objects in it. How is that?

enter image description here

function displayIngredients(cocktail) {
  // console.log(cocktail);
  let ingredients = [];
  console.log(ingredients);


  let i;
  for (i = 1; i < 16; i++) {
    const ingredientsMeasure = {};
    if (cocktail[`strIngredient${i}`] !== '') {
      ingredientsMeasure.ingredient = cocktail[`strIngredient${i}`];
      ingredientsMeasure.measurement = cocktail[`strMeasure${i}`];
      ingredients.push(ingredientsMeasure);
    }
  }
  console.log(ingredients);

}
mplungjan
  • 169,008
  • 28
  • 173
  • 236
Gustavs
  • 73
  • 1
  • 2
  • 8
  • I made you a snippet. Please fix it to make a [mcve] - add the cocktail object – mplungjan Sep 13 '19 at 06:19
  • It's probably just a matter of visualization in the console. Use `console.log(JSON.stringify(ingredients));` to inspect the actual contents at the time of logging. – Robby Cornelissen Sep 13 '19 at 06:20
  • 2
    Do you see that blue "i"? Hover over it, it will give you the answer. – Gerardo Furtado Sep 13 '19 at 06:20
  • Chrome needs a little Clippit character to say _"Looks like you're using `console.log()` to do debugging. That's bad, you should use the debugger instead. Here's how..."_ – Phil Sep 13 '19 at 06:27

1 Answers1

1

console.log() is passed a reference to the object, so the value in the Console changes as the object changes. To avoid that you can:

console.log(JSON.parse(JSON.stringify(ingredients)))
Saksham Gupta
  • 620
  • 6
  • 14