You can do like this:

function coalesce(arr) {
  if (arr.length == 0) return null;
  var v = arr[0];
  v = (typeof v == "function" ? v() : v);
  return v | coalesce(arr.slice(1));
}

Example:

var finalValue = coalesce([ null, null, function(){ return null; }, 5 ]);
// finalValue is now 5
Answer from Guffa on Stack Overflow
🌐
MDN Web Docs
developer.mozilla.org › en-US › docs › Web › JavaScript › Reference › Operators › Optional_chaining
Optional chaining (?.) - JavaScript | MDN
Note: If someInterface itself is null or undefined, a TypeError exception will still be raised ("someInterface is null"). If you expect that someInterface itself may be null or undefined, you have to use ?. at this position as well: someInterface?.customMethod?.(). eval?.() is the shortest way to enter indirect eval mode. 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.
🌐
MDN Web Docs
developer.mozilla.org › en-US › docs › Web › JavaScript › Reference › Operators › Nullish_coalescing
Nullish coalescing operator (??) - JavaScript | MDN
The nullish coalescing operator treats undefined and null as specific values. So does the optional chaining operator (?.), which is useful to access a property of an object which may be null or undefined.
🌐
Mike Bifulco
mikebifulco.com › home › javascript tips: nullish coalescing (??)
JavaScript Tips: Nullish Coalescing (??) | Mike Bifulco
November 15, 2021 - JavaScript's Nullish Coalescing operator is two question mark characters next to one another (??). It takes a left-hand and right-hand operand, returning the right value if the left is null or undefined.
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 .

🌐
CodingNConcepts
codingnconcepts.com › javascript › optional-chaining-operator-javascript
Optional Chaining ?. operator in JavaScript - Coding N Concepts
January 27, 2021 - This is where optional chaining ?. operator comes to the rescue which provides implicit nullish check and make our code even smaller and better. ... Optional chaining ?. operator is introduced in Javascript ES2020 which has following syntax:- obj.val?.prop returns obj.val.prop if val exists, otherwise undefined. obj.func?.(args) returns obj.func(args) if func exists, otherwise undefined. obj.arr?.[index] returns obj.array[index] if array exists, otherwise undefined.
Find elsewhere
🌐
freeCodeCamp
freecodecamp.org › news › javascript-advanced-operators
Advanced JavaScript Operators – Nullish Coalescing, Optional Chaining, and Destructuring Assignment
January 4, 2024 - By using the nullish coalescing operator, you will only replace exactly null and undefined values with the right-hand value.
🌐
V8
v8.dev › features › nullish-coalescing
Nullish coalescing · V8
document.all is a special value that you should never ever ever use. But if you do use it, it’s best you know how it interacts with “truthy” and “nullish”. document.all is an array-like object, meaning it has indexed properties like an array and a length.
🌐
DEV Community
dev.to › laurieontech › nullish-coalescing-let-falsy-fool-you-no-more-41c0
Nullish Coalescing - Let Falsy Fool You No More - DEV Community
December 13, 2019 - And that's what this addition is all about. We can replace our || check with the nullish coalescing operator, ??. Using this operator works much the same as ||, with one major exception. If the value on the left-hand side of the operator is null or undefined the default (right-hand side) will be used.
🌐
freeCodeCamp
freecodecamp.org › news › nullish-coalescing-operator-in-javascript
How the Nullish Coalescing Operator Works in JavaScript
December 22, 2020 - As you have seen, the nullish coalescing operator is really useful when you only care about the null or undefined value for any variable.
🌐
DEV Community
dev.to › jaimaldullat › why-is-the-nullish-coalescing-operator-essential-in-javascript-4g2j
Why Is the Nullish Coalescing Operator(??) Essential in JavaScript? - DEV Community
November 9, 2023 - In this case, the operator is used to check if a specific index in the array is null or undefined, and provide a default value if it is. Both || (Logical OR) and ?? (Nullish Coalescing Operator) are used to provide default values for variables.
🌐
Quora
quora.com › How-do-you-use-the-new-nullish-coalescing-operator-in-JavaScript
How to use the new nullish coalescing operator in JavaScript - Quora
Answer (1 of 2): suppose we have an object like this: [code]const obj = { name: '', count: 0 } [/code]Now, if we want to print initial values of an object “obj” that is the name as an empty string and count as 0 and also want to handle null or undefined cases then we write like this: [cod...
🌐
DEV Community
dev.to › obinnaogbonnajoseph › optional-chaining-and-nullish-coalescing-typescript-3-7-5899
Optional Chaining and Nullish Coalescing - TypeScript 3.7!! - DEV Community
November 6, 2019 - This introduces a new operator ??. It is a way to "fall back" to a default value when dealing with null or undefined.
Top answer
1 of 16
2331

Update

JavaScript now supports the nullish coalescing operator (??). It returns its right-hand-side operand when its left-hand-side operand is null or undefined, and otherwise returns its left-hand-side operand.

Old Answer

Please check compatibility before using it.


The JavaScript equivalent of the C# null coalescing operator (??) is using a logical OR (||):

Copyvar whatIWant = someString || "Cookies!";

There are cases (clarified below) that the behaviour won't match that of C#, but this is the general, terse way of assigning default/alternative values in JavaScript.


Clarification

Regardless of the type of the first operand, if casting it to a Boolean results in false, the assignment will use the second operand. Beware of all the cases below:

Copyalert(Boolean(null)); // false
alert(Boolean(undefined)); // false
alert(Boolean(0)); // false
alert(Boolean("")); // false
alert(Boolean("false")); // true -- gotcha! :)

This means:

Copyvar whatIWant = null || new ShinyObject(); // is a new shiny object
var whatIWant = undefined || "well defined"; // is "well defined"
var whatIWant = 0 || 42; // is 42
var whatIWant = "" || "a million bucks"; // is "a million bucks"
var whatIWant = "false" || "no way"; // is "false"
2 of 16
82
Copyfunction coalesce() {
    var len = arguments.length;
    for (var i=0; i<len; i++) {
        if (arguments[i] !== null && arguments[i] !== undefined) {
            return arguments[i];
        }
    }
    return null;
}

var xyz = {};
xyz.val = coalesce(null, undefined, xyz.val, 5);

// xyz.val now contains 5

this solution works like the SQL coalesce function, it accepts any number of arguments, and returns null if none of them have a value. It behaves like the C# ?? operator in the sense that "", false, and 0 are considered NOT NULL and therefore count as actual values. If you come from a .net background, this will be the most natural feeling solution.

🌐
Flavio Copes
flaviocopes.com › javascript-nullish-coalescing
JavaScript Nullish Coalescing
December 9, 2019 - A powerful operator available in JavaScript is the nullish coalescing operator: ??.
🌐
OpenReplay
blog.openreplay.com › mastering-javascript-optional-chaining-and-nullish-coalescing
Mastering JavaScript: optional chaining and nullish coalescing
In this example, the getUserName function takes an object as an argument and returns the name property of the object if it exists. 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’.
🌐
Reddit
reddit.com › r/typescript › how to access a possibly empty array by index?
r/typescript on Reddit: How to access a possibly empty array by index?
March 19, 2024 -

this is my situation

let matches : string[] | null = topic.match(this._DEVICE_TOPIC_REGEXP);
console.log("handleNewMeasure, topic", topic, "matches", matches);
if (typeof matches === undefined ) {
return;
}
let device_id = matches[1];

I cannot go on because last line warns me that it could be empty