1

This is the weirdest thing I've ever encountered in my programming life.

self.walls = new Array();
self.walls = [];
console.log(self.walls); //Doesn't print an empty array, but an array that contains something

How is this possible? I set self.walls to an empty array in two ways, and it's still full of objects! I'm using the latest version of Google Chrome.

Edit: also, this is the only console.log() in the entire script.

3 Answers 3

3

console.log does not store the state of the object at the time of calling.
At a later point, you've overwritten the self.walls property, which is shown in the console.

If you want to log the true state at the time of executing, you can serialize the object:

// Works for primitives only:
console.log(JSON.parse(JSON.stringify(self.walls)));

// When the array contains another object, the shown referenced object might
//  change
console.log(self.walls.concat()); // Or any other array-copying method.
Sign up to request clarification or add additional context in comments.

3 Comments

That's very strange. Why is it so? So it doesn't pause the execution of a program?
Depends on the implementation. console.log is supposed to take a string argument and print the string in the console.
@Bane It doesn't pause the execution. I have added two methods to print the actual state of the array. If you want to pause the execution, add a debugger; statement.
0

An array has a length, it has methods such as map, shift, unshift, pop, push and so on, and all of these show up in the console because they are properties of the array.

You probably don't see any property named 0, 1, or any other number, right? Those would be the actual array elements, if you'd defined any.

3 Comments

Yes, I see elements. A tonne of them, actually. Also, this isn't really an answer...
It explains what you're seeing. A screenshot might help, but you should not be seeing any elements with a numeric key.
See @Rob's answer above--he is actually seeing elements because console.log doesn't pause execution.
0

As Rob W explained, the console sometimes does not show the true representation of the array when it is called.

However, you mentioned emptying an array but your code ...

self.walls = new Array();
self.walls = [];

...is not emptying the array. It is assigning a new empty array to the property. To empty the array, you can use...

self.walls.length = 0;

1 Comment

@Bane Depends. Do you have other references to that array. If so, the array could not be GC.

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.