30

With below code I noticed that in the browser console when I log the event, the value for currentTarget logs null. However when I log e.currentTarget it logs a value. Any idea's on how that works?

var button = document.getElementById("btn");

var eventButtonHandler = function(e) {
  var button = e.target;
  console.log(e); // logs MouseEvent object with currentTarget:null
  console.log(e.currentTarget); // logs a value
  if(!button.classList.contains("active"))
    button.classList.add("active");
  else
    button.classList.remove("active");
};

button.addEventListener("click", eventButtonHandler);

A jsbin can be found here: http://jsbin.com/xatixa/2/watch?html,js,output

2
  • I suspect it's related to the fact that the objects logged in the console are "live", they're linked to the actual object in memory. So while the handler is running, the target is non-null, but the property changes to null later on, and that's what you see when you expand the object in the console. Commented Oct 22, 2014 at 4:21
  • 1
    Related: stackoverflow.com/questions/37130320/… Commented Jan 27, 2020 at 14:27

1 Answer 1

47

This is an artifact of the way the Javascript console works when you log an object. The log doesn't contain a copy of all the object properties, it just contains a reference to the object. When you click on the disclosure triangle, it then looks up all the properties and displays them.

In this case, at the time you call console.log(e), there's a DOM element in the currentTarget property. But sometime later, that property is reset to null for some reason. When you expand the event object, that's what you see.

A simple example that demonstrates this is:

var foo = { };
for (var i = 0; i < 100; i++) {
    foo['longprefix' + i] = i;
}
console.log(foo);
foo.longprefix90 = 'abc';

When you view the object in the console, you'll see that foo.longprefix90 contains "abc", even though it contained 90 at the time that console.log(foo) was called.

The demonstration needs to use an object with lots of properties. When it's logging, it shows the first few properties that fit in the console, so those are in the early snapshot. Only properties after that display this anomalous behavior.

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

2 Comments

Ah yes, that makes sense. Tnx.
I also encounter this issue just now, with the help of jQuery, i can log the value instead of reference : console.log($.extend({}, e))

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.