Returning the default value for the key that cannot be found in the javascript object

Viewed 1072

When a key that is not in the object is called, it returns undefined. I want to return a string that I specify instead of undefined. for example

let obj = {
  key1: 'key1'
}
let res = obj.key2;

console.log(res);

I want console.log (res) to return "key not found", not undefined.

Is this possible?

1 Answers

You could take the Nullish coalescing operator ??, which repects other falsy values than undefined or null.

let obj = { key1: 'key1' },
    res = obj.key2 ?? 'key2 not found';

console.log(res);

If undefined/null are real values, the key should be checked in advance.

let obj = { key1: null },
    res = 'key1' in obj ? obj.key1 : 'key2 not found';

console.log(res);

Related