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

JavaScript

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

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

JavaScript
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement