0

I have this:

const className = ev.target && ev.target.className;

in some cases typeof classname === 'object'...does anyone know why that's the case and when it might be the case? I always thought it must be a string.

I actually found a case where it's an object on the StackOverflow page, but I can't find the element again.

  • 1
    `classname` or `className`? We need a reproducible example. Generally, it’s never an object. Perhaps you meant `classList` which is always an object. – Sebastian Simon Jan 14 '18 at 23:39
  • 1
    If **ev.target** is **null** then you will have an object in *className*. – some Jan 14 '18 at 23:44
  • I don't think `ev.target && ev.target.className` is the same as `(typeof ev.target !== undefined) ? ev.target.className : ''`, which is probably closer to what you intended. – Vince Jan 14 '18 at 23:44

2 Answers2

2

If ev.target is a truthy value, then the value of ev.target.className will be assigned to className, but if it was falsy, the falsy value will be assigned.

For example, it ev.target is null, typeof className will return object since null is an object.

some
  • 48,070
  • 14
  • 77
  • 93
-4

You're assigning a Boolean value to the className variable. Boolean is an object.

Vince
  • 3,962
  • 3
  • 33
  • 58
  • There’s no `Boolean` object in the code at all. `Boolean` itself is a function. – Sebastian Simon Jan 14 '18 at 23:45
  • Doesn't `ev.target && ev.target.className` return the value `true` or `false`? I thought that would count as an instance of Boolean. – Vince Jan 14 '18 at 23:48
  • No, you have misunderstood the code. If *ev.target* is a [trythy](https://developer.mozilla.org/en-US/docs/Glossary/Truthy) then the value of *ev.target.className* will be assigned. If it is [Falsy](https://developer.mozilla.org/en-US/docs/Glossary/Falsy) the falsy value will be assigned. – some Jan 14 '18 at 23:48
  • 1
    [Why don't logical operators (&& and ||) always return a boolean result?](https://stackoverflow.com/q/5417969/4642212) – Sebastian Simon Jan 14 '18 at 23:49