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
This is an idiomatic pattern in JavaScript, but it gets verbose when the chain is long, and it's not safe. For example, if obj.first is a Falsy value that's not null or undefined, such as 0, it would still short-circuit and make nestedProp become 0, which may not be desirable. With the optional ...
🌐
JavaScript.info
javascript.info › tutorial › the javascript language › objects: the basics
Optional chaining '?.'
The optional chaining ?. is not an operator, but a special syntax construct, that also works with functions and square brackets. For example, ?.() is used to call a function that may not exist.
🌐
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.
🌐
GeeksforGeeks
geeksforgeeks.org › javascript-optional-chaining
JavaScript Optional Chaining | GeeksforGeeks
May 17, 2025 - TypeScript Optional Chaining: TypeScript Optional Chaining is the process of searching and calling variables, methods, parameters that might be nil in existence.This par ... Introduction : Optional is an immutable object that may contain a non-null reference to another object. Each instance of this type either contains a non-null reference, or contains nothing, in which case we say that the reference is absent. It is never said to contain null. Example : Hashmap.get(key
🌐
DEV Community
dev.to › codeofrelevancy › javascripts-optional-chaining-operator-3pfn
JavaScript's Optional Chaining (?.) Operator - DEV Community
March 28, 2023 - It's important to note that the Optional Chaining operator cannot be used on a non-declared root object. Attempting to do so will result in a ReferenceError being thrown, indicating that the root object is not defined. However, the operator can be used on a root object that has a value of undefined. If you've just started to read the tutorial and learn JavaScript, maybe the problem hasn't touched you yet, but it's quite common. As an example, let's say we have user objects that hold the information about our users.
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 .

🌐
freeCodeCamp
freecodecamp.org › news › javascript-optional-chaining
How to Use Optional Chaining in JavaScript
February 7, 2022 - Optional chaining is a safe and concise way to perform access checks for nested object properties. 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 va...
🌐
TutorialsPoint
tutorialspoint.com › javascript › javascript_optional_chaining.htm
JavaScript - Optional Chaining
When any object property doesn't exist, the optional chain stops the code execution and returns undefined. If you use the JavaScript nullish coalescing operator with it, you can return the default value when the object property doesn't exist.
Find elsewhere
🌐
V8
v8.dev › features › optional-chaining
Optional chaining · V8
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.
🌐
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. Similarly, if a function does not exist, it returns `undefined`. However, if you are looking for extra information, I recommend you read the MDN docs explanation here (click-me). Coming back to our previous example, let's see how can we shorten the if statement.
🌐
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?

🌐
GitHub
github.com › tc39 › proposal-optional-chaining
GitHub - tc39/proposal-optional-chaining
No. 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:
Starred by 4.9K users
Forked by 72 users
Languages   HTML 97.2% | Shell 2.8%
🌐
Dmitri Pavlutin
dmitripavlutin.com › javascript-optional-chaining
How to Use JavaScript Optional Chaining
Nullish coalescing can improve the optional chaining by defaulting to a value when the chain evaluates to undefined. For example, let's change getLeading() function to return "Unknown actor" when there are no actors in the movie object:
🌐
Codecademy
codecademy.com › docs › javascript › optional chaining
JavaScript | Optional Chaining | Codecademy
August 7, 2025 - Learn how to use JavaScript — a powerful and flexible programming language for adding website interactivity. Beginner Friendly.Beginner Friendly15 hours15 hours · The basic syntax for using optional chaining is as follows: // To access an object property object?.property; //To access an element in an array array?.[index]; //To invoke a function (if it exists) object?.method?.(); ... Run the following example and compare the regular syntax of conditional statements and optional chaining on a more complex data set:
🌐
JavaScript Tutorial
javascripttutorial.net › home › javascript tutorial › javascript optional chaining operator
JavaScript Optional Chaining Operator (?.)
December 17, 2023 - To access a property of an object using the optional chaining operator, you use one of the following: objectName ?. propertyName objectName ?. [expression]Code language: JavaScript (javascript)
🌐
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.
🌐
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".
🌐
Reality Ripple
udn.realityripple.com › docs › Web › JavaScript › Reference › Operators › Optional_chaining
Optional chaining (?.) - JavaScript
You can also use the optional chaining operator when accessing properties with an expression using the bracket notation of the property accessor: ... let object = {}; object?.property = 1; // Uncaught SyntaxError: Invalid left-hand side in assignment ... This example looks for the value of the name property for the member bar in a map when there is no such member.
🌐
W3Schools
w3schools.com › js › js_2020.asp
JavaScript 2020
The Optional Chaining Operator returns undefined if an object property is undefined or null (instead of throwing an error).
🌐
2ality
2ality.com › 2019 › 07 › optional-chaining.html
ES2020: optional chaining
This behavior differs from a normal operator/function where JavaScript always evaluates all operands/arguments before evaluating the operator/function. It is called short-circuiting. Other short-circuiting operators: ... Until now, the following alternatives to optional chaining were used in ...