Has a function been executed after declaration?

function a(x){
			let onesArray=[];
			console.log(onesArray);
			for(let i=0;i<x;i++){
				onesArray.push(1);
			}
			return onesArray;
		}
		a(3);

“console.log()” is just below the statement that assigns the array an empty value. But the browser console shows the array is “[1,1,1]”. Why?

Because of this line

so the “console.log()” is executed after “for loop”?

The console.log is the empty array but you will also see the result from the for loop which is the [1,1,1]

You can see it here when I ran your code in the chrome developer tools.
Screen Shot 2020-12-23 at 8.24.15 PM


I can only see one result. :joy:

hmm that’s weird.

I just ran the code you gave me and got a different result.

Not sure why though :laughing:

Your console.log worked for me

I change the code to console.log("result is"+onesArray);
the console.log is:
image
So, the array is really empty.
Maybe when console.log is empty, the console will show the executed array as if there is a code console.log(a(3))
Anyway, thank you for your replay! :grinning:

One interesting thing about this is try and remove the console.log and run the code in Dev Tools. what you see is (3) [1, 1, 1] which is from the return oneArray.

So the console log runs one time before the for loop and accounts for why, Jessica, you were seeing [ ] on one line then (3) [1, 1, 1] on the second line.

I was also confused why the console log would run twice in this function (and it doesn’t - it only runs once). We would have to run it after the for loop to see (3) [1, 1, 1] but really because the return also shows the same, it’s really (3) [1, 1, 1] twice.

You should get two outputs. One will be an empty array that you’re printing out in the 3rd line console.log(onesArray). It’s empty simply because you’re printing it out before looping through and adding the numbers (1 in this case). And the 2nd output will be the one because of the return statement that’s returning the modified array (by the for loop in this case) which will be an array consisting of 3 1’s like this one: [1, 1, 1] but it won’t print out the output because you haven’t put the function call a(3) inside a console.log(), so replace it by console.log(a(3)) and the problem should be fixed!

Hope this makes things clearer.

1 Like

This will depend on the environment that you are executing your code in. Some consoles will display the returned value as well as the logged values.

1 Like