0

I ran the following JS code. Console prints an empty array.

function xyz(){
var a=[]; var b=[];
console.log(a);
for(i=0;i<10;i++){
b.push(i);
}
a=b;
}
but when I try to run this

function xyz(){
var a=[];
console.log(a);
for(i=0;i<10;i++){
a.push(i);
}
}

the console prints the array from 0 to 9. Also, I see here that even though the console statement is above the for loop where we are pushing the values in the array, but still the console is printing but not in the first case (which i think is because the reference which console is printing is empty).Code was tested on chrome browser console.

4
  • None of the console print anything Commented Jun 26, 2018 at 6:59
  • Both the consoles are blank. Commented Jun 26, 2018 at 6:59
  • I cannot see what you are saying... both print an emtpy array Commented Jun 26, 2018 at 7:01
  • @AnkitAgarwal Copy paste the code and try running in your chrome browser console.Even I am getting empty array in Stack overflow . Commented Jun 26, 2018 at 7:04

1 Answer 1

2
function xyz(){
   var a=[];
   console.log(a);
   for(var i=0;i<10;i++){
     a.push(i);
   }
}
xyz();

When we see it in chrome console it has a empty array but when we expand it , it is showing array values with length property as well.

You need to pay a close attention there, there is an i (info) which says, it is evaluated just now.

enter image description here

This means, chrome console gets a live reference to the array and showing blank array with length property equal to 0 on console.log() but also adding live reference to that array, so on expanding we see array

You need to use console.log() after array is updated in your code to work properly.

  function xyz(){
      var a=[];
       
      for(i=0;i<10;i++){
         a.push(i); //array is updating here
      }
     console.log(a);
    }
    xyz();

 

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

4 Comments

yeah I know that. But try to run the given code in the crude form, as I have written, in your local browser console.
@user3847870 added explanation for chrome console as well, see if it answers your question !
It will show evaluated just now in other case also.Please try running both scenarios.
@user3847870 Yes, true for other case as well. My point was that it is attaching live reference, it is returning empty array but on expanding it, it gives current array status (elements, length etc.). I think this attaching live reference is true for within its scope

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.