0

This is probably very silly but I have been reading the code too long and can't seem t find why is my variable not printing empty in the console if it hasn't reached the function where is actually pushing values into it. It works fine, I just want to understand why.

I've printed many console.log to track any line of code where I'm filling the variable (it's an array), I've also tried different things in other parts of the code but it is a const variable, so it can be assigned a different value from outside the function.

function ABC() {

  console.log('FUNCTION BEGINS...');
  const tempDates: Array<Moment> = [];
  console.log(tempDates);
  console.log('After creating the variable...');

  console.log('Before log tempdates');
  console.log(tempDates);

  const start_date = this.date;

  let dateToAdd = start_date;
  tempDates.push(dateToAdd);

  console.log(dateToAdd);
  console.log(tempDates);
}

Maybe I'm wrong and over analyzing but I would expect the first time I print the const 'tempDates' to print an empty array. but actually outputs the array with 3 dates inside, which are actually filled if a condition is true, many lines of code after.

This is how the console looks like: Each log printed is as the code shows. (same order)

1 Answer 1

1

This is because of the way that the Chrome console handles objects these days. It will essentially print a pointer to the contents of that object - if the contents change, the output in the console will, too. In order to get an accurate view of what an object or array looks like at a given point in time in the console, be sure to use JSON.stringify() or .toString() in your console.log() statement to convert it to a string that will not change.

console.log(JSON.stringify(myArray))

console.log(myArray.toString())

Here's an article explaining this if you're interested.

That being said, your code is working as intended, Chrome is just being deceptive.

Sign up to request clarification or add additional context in comments.

1 Comment

@dracarons Glad I could help. I've been bitten by this more than once as well!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.