You need to put a . after the ? to use optional chaining:

myArray.filter(x => x.testKey === myTestKey)?.[0]

Playground link

Using just the ? alone makes the compiler think you're trying to use the conditional operator (and then it throws an error since it doesn't see a : later)

Optional chaining isn't just a TypeScript thing - it is a finished proposal in plain JavaScript too.

It can be used with bracket notation like above, but it can also be used with dot notation property access:

const obj = {
  prop2: {
    nested2: 'val2'
  }
};

console.log(
  obj.prop1?.nested1,
  obj.prop2?.nested2
);
Run code snippetEdit code snippet Hide Results Copy to answer Expand

And with function calls:

const obj = {
  fn2: () => console.log('fn2 running')
};

obj.fn1?.();
obj.fn2?.();
Run code snippetEdit code snippet Hide Results Copy to answer Expand

Answer from CertainPerformance on Stack Overflow
🌐
MDN Web Docs
developer.mozilla.org › en-US › docs › Web › JavaScript › Reference › Operators › Optional_chaining
Optional chaining (?.) - JavaScript | MDN
You can also use the optional chaining operator with bracket notation, which allows passing an expression as the property name: ... This is particularly useful for arrays, since array indices must be accessed with square brackets.
Top answer
1 of 5
589

You need to put a . after the ? to use optional chaining:

myArray.filter(x => x.testKey === myTestKey)?.[0]

Playground link

Using just the ? alone makes the compiler think you're trying to use the conditional operator (and then it throws an error since it doesn't see a : later)

Optional chaining isn't just a TypeScript thing - it is a finished proposal in plain JavaScript too.

It can be used with bracket notation like above, but it can also be used with dot notation property access:

const obj = {
  prop2: {
    nested2: 'val2'
  }
};

console.log(
  obj.prop1?.nested1,
  obj.prop2?.nested2
);
Run code snippetEdit code snippet Hide Results Copy to answer Expand

And with function calls:

const obj = {
  fn2: () => console.log('fn2 running')
};

obj.fn1?.();
obj.fn2?.();
Run code snippetEdit code snippet Hide Results Copy to answer Expand

2 of 5
50

Just found it after a little searching on the what's new page on official documentation

The right way to do it with array is to add . after ?

so it'll be like

myArray.filter(x => x.testKey === myTestKey)?.[0] // in case of object
x?.() // in case of function

I'll like to throw some more light on what exactly happens with my above question case.

myArray.filter(x => x.testKey === myTestKey)?[0]

Transpiles to

const result = myArray.filter(x => x.testKey === myTestKey) ? [0] : ;

Due to which it throws the error since there's something missing after : and you probably don't want your code to be transpilled to this.

Thanks to Certain Performance's answer I learned new things about typescript especially the tool https://www.typescriptlang.org/play/index.html .

🌐
DEV Community
dev.to › joelynn › optional-chaining-objects-arrays-2mjk
Optional Chaining (objects & arrays) - DEV Community
June 10, 2021 - The benefit of optional chaining on an array is that if the results were null or undefined, your code won't break.
🌐
freeCodeCamp
freecodecamp.org › news › optional-chaining-javascript
Optional Chaining in JavaScript – Explained with Examples
February 13, 2024 - Here, the optional chaining operator is used to call the getAddress() method and access its city property. If getAddress method or any intermediate property in the chain is null or undefined, the expression short-circuits, and the result is immediately set to "Unknown". In this example, we have an array of users, where each user may or may not have a profile.
🌐
Codecademy
codecademy.com › docs › javascript › optional chaining
JavaScript | Optional Chaining | Codecademy
August 7, 2025 - Optional chaining can be used to validate nested object properties, call optional functions or methods on optional objects, accessing array elements, and more. The primary benefits of using optional chaining instead of regular syntax include ...
🌐
egghead.io
egghead.io › lessons › egghead-safely-access-a-property-on-a-javascript-array-with-optional-chaining
Safely Access a Property on a JavaScript Array with Optional Chaining | egghead.io
You can use optional chaining to access elements in an array. If the array is null or undefined, attempting to access an element with optional chaining ...
Published   April 3, 2020
🌐
JavaScript.info
javascript.info › tutorial › the javascript language › objects: the basics
Optional chaining '?.'
E.g. in user?.address.street.name the ?. allows user to safely be null/undefined (and returns undefined in that case), but that’s only for user. Further properties are accessed in a regular way. If we want some of them to be optional, then we’ll need to replace more .
Find elsewhere
🌐
Fjolt
fjolt.com › article › javascript-optional-chaining
How does Optional Chaining work in Javascript?
Optional chaining can also be used with arrays. For example - if you aren’t sure if a property will be defined, but it contains an array. Below, a user can have an array of valid addresses, and we want to get the first line of their address, from their first address.
🌐
Dmitri Pavlutin
dmitripavlutin.com › javascript-optional-chaining
How to Use JavaScript Optional Chaining
Optional chaining accesses properties from deep of nested objects without prop existence verification and intermediate variables boilerplates.
🌐
V8
v8.dev › features › optional-chaining
Optional chaining · V8
What happens when db, user, or name is undefined or null? With the optional chaining operator, JavaScript initializes nameLength to undefined instead of throwing an error.
🌐
daily.dev
daily.dev › home › blog › webdev › optional chaining in javascript - what is it and how to use it?
Optional Chaining In JavaScript - What Is It And How To Use It?
November 1, 2021 - The optional chaining feature is similar to the `.` chaining operator. The only difference is that it returns the value of undefined if the reference is `null` or `undefined`. That is if the object property does not exist.
🌐
DEV Community
dev.to › codeofrelevancy › javascripts-optional-chaining-operator-3pfn
JavaScript's Optional Chaining (?.) Operator - DEV Community
March 28, 2023 - The syntax is straightforward and easy to understand. The operator is placed after the object you wish to access and before the property, array expression, or function call you want to make.
🌐
Medium
medium.com › @ajithr116 › optional-chaining-in-javascript-21348de56ac0
optional chaining in javascript. Optional chaining in JavaScript is a… | by Ajith R | Medium
August 22, 2024 - The syntax for optional chaining uses the `?.` operator: ```javascript let streetName = user?.profile?.address?.street; ``` In this example, if `user`, `profile`, or `address` is `null` or `undefined`, the expression will short-circuit and return `undefined` instead of causing an error. ... If `method` is `null` or `undefined`, the entire expression returns `undefined` without attempting to call `method`. ... This is particularly useful when working with arrays that might be `null` or `undefined`.
🌐
Designcise
designcise.com › web › tutorial › how-to-use-javascript-optional-chaining-with-array
How to Use JavaScript Optional Chaining With Array? - Designcise
January 9, 2022 - You can use optional chaining (?.) with an array by adding the ?. symbol before the array index accessor, like so: // ES11+ array?.[index] For example: // ES11+ const arr = ['foo', 'bar', 'baz']; console.log(arr?.[0]); // 'foo' console.log(arr?.[10]); // undefined
🌐
Web Dev Simplified
blog.webdevsimplified.com › 2020-03 › javascript-optional-chaining
JavaScript Optional Chaining
If the arr variable is not defined then undefined will be returned instead of trying to access the index of the array. This bracket notation optional chaining can also be used with objects as well.
🌐
EyeHunts
tutorial.eyehunts.com › home › optional chaining array in javascript | example code
Optional Chaining Array in JavaScript | Example code
August 16, 2023 - Note: Optional chaining is only used for reading not for assignments. Simple example code used with bracket notation like above, but it can also be used with dot notation property access. <!DOCTYPE html> <html> <body> <script> const user = { name: 'JOhn', age: 25, settings: { theme: { mode: 'dark', text: '#d7e0ff', background: '#f87070', font: 'Kumbh Sans, sans-serif' }, }, friends: ['Tim', 'Steve', 'Mike'], } // use optional chaining const first = user?.friends?.[0] console.log(first) console.log(user?.friends) </script> </body> </html>
🌐
Byby
byby.dev › js-optional-chaining
JavaScript Optional Chaining
Similarly, we are using optional chaining to safely access the city property of the address object of the second item in the users array, which does not exist. ... A lightweight macOS app that turns text into speech totally offline. Featured ContentMy Favorite ReferencesGuest Posting GuidelinesBecome a Fullstack JS DeveloperCracking the iOS interviewMastering JavaScriptMastering TypeScriptWhat's New in SwiftMastering Swift and SwiftUIMastering Web DevelopmentCSS for Beginners
🌐
TutorialsPoint
tutorialspoint.com › javascript › javascript_optional_chaining.htm
JavaScript - Optional Chaining
Here, the optional chaining operator (?.) comes into the picture to solve the non-existing property problem easily. In JavaScript, optional chining operator (?.) is introduced in ECMAScript 2020 (ES2020). It provides the best way to access object properties, array elements, etc.
🌐
GeeksforGeeks
geeksforgeeks.org › typescript › how-to-use-optional-chaining-with-arrays-and-functions-in-typescript
How to use Optional Chaining with Arrays and Functions in TypeScript ?
May 6, 2024 - In this approach, we are using optional chaining with array elements, where we are accessing the first author in the authors array of the geeksArticle object. We are storing the result in mainAuth, which prints the author name or 'undefined' if the authors array is not defined or empty. const result = object?.property?.[index]?.method(); Example: Below is the implementation of the above-discussed approach. JavaScript ·