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
The optional chaining (?.) operator accesses an object's property or calls a function. If the object accessed or function called using this operator is undefined or null, the expression short circuits and evaluates to undefined instead of throwing an error.
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 .

๐ŸŒ
JavaScript.info
javascript.info โ€บ tutorial โ€บ the javascript language โ€บ objects: the basics
Optional chaining '?.'
let user = null; let x = 0; user?.sayHi(x++); // no "user", so the execution doesn't reach sayHi call and x++ alert(x); // 0, value not incremented ยท The optional chaining ?. is not an operator, but a special syntax construct, that also works with functions and square brackets.
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ javascript โ€บ javascript-optional-chaining
JavaScript Optional Chaining - GeeksforGeeks
user3.dog() causes a TypeError because dog does not exist on user3, so JavaScript cannot call it as a function. Using optional chaining with function calls (user3.dog?.()) safely skips the call when the function is undefined, preventing the error.
Published ย  June 22, 2020
๐ŸŒ
Reddit
reddit.com โ€บ r/node โ€บ conditionally call a function with optional chaining.
r/node on Reddit: Conditionally call a function with optional chaining.
November 10, 2020 - Seems like something is being used incorrectly further up the chain. ... Yep. And that's why kids, always use Typescript โค๏ธ ... Typescript doesn't add runtime type checks, you still have to do that yourself if you're accepting multiple types (in this case function | undefined). So no. ... unless you used a type of filter callback, and instead allowed just an object / string to be passed in? interface OptionsForSomething { filter: ((x: string) => boolean) | string; }
๐ŸŒ
JavaScript Tutorial
javascripttutorial.net โ€บ home โ€บ javascript tutorial โ€บ javascript optional chaining operator
JavaScript Optional Chaining Operator (?.)
December 17, 2023 - function getUser(id, callback) { // get user // ... let user = { id: id, username: 'admin' }; // test if the callback exists if ( callback ) { callback(user); } return user; }Code language: JavaScript (javascript) By using the optional chaining operator, you can skip the test if the callback exists:
๐ŸŒ
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.
๐ŸŒ
V8
v8.dev โ€บ features โ€บ optional-chaining
Optional chaining ยท V8
Some other languages offer an elegant ... chain is a chain of one or more property accesses and function calls, the first of which begins with the token ?.โ€. Using the new optional chaining operator, we can rewrite the above example as follows: // Still checks for errors and is much more readable. const nameLength = db?.user?.name?.length; 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...
Find elsewhere
๐ŸŒ
Scaler
scaler.com โ€บ topics โ€บ javascript-optional-chaining
How to Use Optional Chaining in JavaScript? - Scaler Topics
February 1, 2023 - We use optional chaining in Javascript to access nested properties of objects. It returns undefined if some intermediate property of the object does not exist. It solves the problem that occurs due to non-existing properties of objects. Optional chaining can be used with function calls, ...
๐ŸŒ
GitHub
github.com โ€บ tc39 โ€บ proposal-optional-chaining
GitHub - tc39/proposal-optional-chaining
Optional Chaining just checks whether some value is undefined or null. It does not catch or suppress errors that are thrown by evaluating the surrounding code. For example: (function () { "use strict" undeclared_var?.b // ReferenceError: ...
Starred by 4.9K users
Forked by 72 users
Languages ย  HTML 97.2% | Shell 2.8%
๐ŸŒ
TutorialsPoint
tutorialspoint.com โ€บ javascript โ€บ javascript_optional_chaining.htm
JavaScript - Optional Chaining
In JavaScript, you can also use the optional chaining with the function calls. If the function is not defined, it will return the undefined.
๐ŸŒ
freeCodeCamp
freecodecamp.org โ€บ news โ€บ javascript-optional-chaining
How to Use Optional Chaining in JavaScript
February 7, 2022 - The optional chaining operator ?. takes the reference to its left and checks if it is undefined or null. If the reference is either of these nullish values, the checks will stop and return undefined.
๐ŸŒ
Byby
byby.dev โ€บ js-optional-chaining
JavaScript Optional Chaining
If the operand at the left-hand side of the ?. operator evaluates to undefined or null, the right-hand side will not be evaluated as short-circuiting, the expression evaluates to undefined. Otherwise the targeted property access, method or function call is triggered normally. a?.[++x] // `x` is incremented if and only if `a` is not null/undefined ยท Optional chaining pairs well with nullish coalescing ??
๐ŸŒ
Reality Ripple
udn.realityripple.com โ€บ docs โ€บ Web โ€บ JavaScript โ€บ Reference โ€บ Operators โ€บ Optional_chaining
Optional chaining (?.) - JavaScript
If you use callbacks or fetch methods from an object with a destructuring assignment, you may have non-existent values that you cannot call as functions unless you have tested their existence. Using ?., you can avoid this extra test: // Written as of ES2019 function doSomething(onContent, onError) { try { // ... do something with the data } catch (err) { if (onError) { // Testing if onError really exists onError(err.message); } } } // Using optional chaining with function calls function doSomething(onContent, onError) { try { // ...
๐ŸŒ
OpenReplay
blog.openreplay.com โ€บ mastering-javascript-optional-chaining-and-nullish-coalescing
Mastering JavaScript: optional chaining and nullish coalescing
If the name property is null or undefined, the Optional Chaining operator( ?.) will return null or undefined, and the Nullish Coalescing operator (??) will use the default value of โ€˜John Doeโ€™. The getUserName function is then called with four different arguments:
๐ŸŒ
Reddit
reddit.com โ€บ r/javascript โ€บ [askjs] over-using optional chaining. is this pattern common?
r/javascript on Reddit: [AskJS] Over-using optional chaining. Is this pattern common?
January 18, 2021 -

Hi everyone!

I love optional chaining, i really do, but there are some cases where using this syntax damages the readability of the code. One of those cases is the following

function optionalFunction(){     
    console.log("works"); 
}  
// optionalFunction = undefined;  

optionalFunction?.(); 

While i understand this approach, i find it optionalFunction?.() harder to read as opposed to this

function optionalFunction(){     
    console.log("works"); 
}  
// optionalFunction = undefined;  

if(optionalFunction != undefined){     
    optionalFunction(); 
} 

I think i'd rather have a more readable and stronger check than ES6 magic when checking if an optional function is defined.

I believe that optional chaining fixes the problem of checking if a property of an object exists, and if exists, then get the value or keep going deeper in the object structure. But this syntax just looks weird for calling functions, it looks a lot like those "one line cleverness" code that sometimes people encounter.

What are your thoughts about this?

๐ŸŒ
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 ...
๐ŸŒ
Dmitri Pavlutin
dmitripavlutin.com โ€บ javascript-optional-chaining
How to Use JavaScript Optional Chaining
For example, let's change getLeading() function to return "Unknown actor" when there are no actors in the movie object: ... You can use optional chaining in the following 3 forms. The first form object?.property is used to access a static property: ... What's interesting about the optional chaining operator is that as soon as a nullish value is encountered on its left-hand side leftHandSide?.rightHandSide, the evaluation of the right-hand side accessors stops. This is called short-circuiting.
๐ŸŒ
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.
๐ŸŒ
freeCodeCamp
freecodecamp.org โ€บ news โ€บ javascript-optional-chaining-explained
JavaScript Optional Chaining `?.` Explained - How it Works and When to Use it
August 25, 2020 - let familyTree = { us: { children: {} } } // with _.get const grandChildren = _.get(familyTree, 'us.children.theirChildren', 'got no kids' ); //with optional chaining and null coalescing const nullCoalescing = familyTree?.us?.children?.theirChildren ?? 'got no kids' console.log(nullCoalescing) //got no kids ยท It also works for objects that may be null or undefined: ... Try it in your browser's console: This is a recent addition and old browsers may need polyfills. You can try it in Chrome or Firefox in the browser's console. If it doesn't work, try turning on JavaScript experimental features by visiting chrome://flags/ and enabling "Experimental JavaScript".