Why is that...?

In the image above, why do we need (e.target.nodeName) in order to get the result in the condition. And the requirement (e.target == ‘P’), for example, wasn’t enough in the condition.
Alternatively, we can just use (e.target.nodeName == ‘p’) in the condition, to get the result.

I’m not exaclty sure, if I understand you correctly. Do you mean why is it written like

(e.target && e.target.nodeName == 'P')

and not just

(e.target.nodeName == 'P')

This is a good practice to make your code more robust. It first checks if e.target really exists, before using one of its properties. If it doesn’t exist, the if() evaluation is false and it won’t check the second part. If you just use e.target.nodeName == 'P' and - for whatever reason - e.target doesn’t exist, an error will be thrown.

Hope that helps!
Michael

That’s some of what I meant thanks, but why can’t I just use (e.tartget == ‘p’ ) to get the result.

Ahh, now I understand. Sorry.

e.target is an object that has all the information about the element that was clicked (not just the name). For example its width and height and a lot of other things. One of its properties is nodeName which is the actual name of the tag as an uppercase string ("DIV", "P" etc.).

Does that make it clearer?
Michael

1 Like

This is more than obvious :grin:
Thanks