javascriptdomdom-events

Why currentTarget value is null


I am learing event.target and event.currentTarget. I think i am clear with the difference between the two. But stuck in a situation where event.currentTarget value turns out to be null.

Following are the HTML and JS code snippets:

HTML code

<form id="form">
   This is a form
</form>

JavaScript Code

 form.addEventListener('click', func);

 function func(event) {
    console.log(event.target.tagName);  //line1
    console.log(event.currentTarget.tagName); //line2

    setTimeout(()=> {
       console.log(event.target.tagName);  //line3
       console.log(event.currentTarget.tagName); //line4
    }, 0)  ;
 }

My doubt is that in line1 and line3 I got the value of event.target the same. But there is a difference in the value of event.currentTarget in line2 and line4.

The output in line3 is 'form', but in line4 it is:

Uncaught TypeError: Cannot read property 'tagName' of null.

That means currentTarget is null in line4.

Can you explain why value of currentTarget is null in line4 ?


Solution

  • https://developer.mozilla.org/en-US/docs/Web/API/Event/currentTarget. Note the line

    Note: The value of event.currentTarget is only available while the event is being handled. If you console.log() the event object, storing it in a variable, and then look for the currentTarget key in the console, its value will be null`.