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
JavaScript
x
6
1
let obj = {
2
key1: 'key1'
3
}
4
let res = obj.key2;
5
6
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
.
JavaScript
1
4
1
let obj = { key1: 'key1' },
2
res = obj.key2 ?? 'key2 not found';
3
4
console.log(res);
If undefined
/null
are real values, the key should be checked in advance.
JavaScript
1
4
1
let obj = { key1: null },
2
res = 'key1' in obj ? obj.key1 : 'key2 not found';
3
4
console.log(res);