Skip to content
Advertisement

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

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?

Advertisement

Answer

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);
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement