1

In my code, I have a variable containing an array. I want to debug manipulations of that variable. I do not mind if the contents of the array are changing, but I have to see how often and when the array itself changes.

An example:

window.myarray = []
console.log(window.myarray); // outputs: []

window.myarray.push("bla"); // an irrelevant manipulation
console.log(window.myarray); // outputs: ["bla"]

window.myarray = ["bla"]; // a change of the array's identity!
console.log(window.myarray); // still outputs: ["bla"]

How can I detect, that the array that is stored in a variable has changed, even if the content of the old and new arrays are the same?

1
  • Store a temporary reference to window.myarray's state you want to detect it changing from. E.g tmp = window.myarray Commented Sep 10, 2018 at 11:05

2 Answers 2

5

You could use proxies

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy

Or you can define a property on window

(function() {
  let _myArray;
  Object.defineProperty(window, "myArray", {
    set(value) {
      _myArray = value;
      console.log('changed', value);
    },
    get() {
      return _myArray
    }
  })
}())

window.myArray = [];

window.myArray = ['bar'];

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/defineProperty

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

1 Comment

console.error would be slightly better as it includes the stack trace.
3

You check the identity like this:

window.myarray = []
var backup = window.myarray;

window.myarray.push("bla"); // an irrelevant manipulation
console.log(backup === window.myarray); // true

window.myarray = ["bla"]; // a change of the array's identity!
console.log(backup === window.myarray); // false

Note that backup isn't an actual copy, just a reference to the same in-memory object.

4 Comments

This is already helpful, but I would prefer to be able to compare it in the console log.
@slartidan I don't understand what you mean by that, at all.
I would like to output something in the console log, that uniquely identifies an instance of an array. So that I can check afterwards if two logged arrays are identical or not.
@slartidan I see; according to this there's no way to grab the memory address like for instance Java prints as default toString().

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.