1

I'm new in JS and I can't figure out what this question mark means in this line: .querySelector('button')?.removeEventListener ..

I know what a ternary operator is, but this doesn't look like it.

Thanks

Reporter
  • 3,897
  • 5
  • 33
  • 47
  • https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Optional_chaining – Dave Newton Aug 03 '21 at 15:24
  • See [How the Question Mark (?) Operator Works in JavaScript](https://www.freecodecamp.org/news/how-the-question-mark-works-in-javascript/). – jarmod Aug 03 '21 at 15:25
  • 1
    See [What does this symbol mean in JavaScript?](/q/9549780/4642212) and the documentation on MDN about [expressions and operators](//developer.mozilla.org/docs/Web/JavaScript/Reference/Operators) and [statements](//developer.mozilla.org/docs/Web/JavaScript/Reference/Statements). – Sebastian Simon Aug 03 '21 at 15:25

2 Answers2

1

Optional chaining (?.) The optional chaining operator (?.) enables you to read the value of a property located deep within a chain of connected objects without having to check that each reference in the chain is valid.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Optional_chaining

Eyescream
  • 902
  • 5
  • 14
  • Thanks man! That link helped me. When I googled at myself, I was constantly kicked out by a ternary operator. Thanks! – devBeginner Aug 03 '21 at 15:30
1

It's called the Short-circuit evaluation and it's a feature of TypeScript. Not JavaScript .

When whatever before ? Is null or undefined, whatever after ?. Won't be called. That's to avoid errors like: undefined has no property removeEventListener

Edit

I was wrong when I said it's not a feature of JavaScript. It's actually a new feature. Some browsers that are not updated to the latest don't support it yet (like mine)

TSR
  • 17,242
  • 27
  • 93
  • 197