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 OverflowVideos
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
This function works perfectly for me:
function coalesce(...param){
if (param.length == 0) return null;
return param.find(a => a !== null);
}
let value = coalesce(null, null, 1,2,3,4);
console.log('value = ', value );
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
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 .
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"
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.
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