Skip to content
Advertisement

How to safe get value from object (return null when not exist)

I want to lookup for a key on an object, but if the key does’t exist, it must return null, is it possible in JavaScript?

const d = {
  A: () => { return 'A' },
  B: () => { return 'B' },
  C: () => { return 'C' },
}

const key = 'Z'

const func = d[key] // HERE

console.log(func)

Advertisement

Answer

You can use or: ||

or the newer optional chaining and Nullish coalescing operator

NOTE: the arrow function suggested by Máté Wiszt has to be wrapped in () or it will give an error

const d = {
  A: () => { return 'A' },
  B: () => { return 'B' },
  C: () => { return 'C' },
}

let key = 'A'

let func = d[key] || null;
console.log(func && func())

key = 'Z'

func = d[key] || null
console.log(func && func())

func = d[key] || function() { return null };
console.log(func && func())

func = d?.[key] ?? (() => null); // arrow has to be wrapped
console.log(func())

// undefined key
let key1;
console.log({key1})

func = d?.[key1] ?? (() => null); // arrow has to be wrapped
console.log("Using undefined key1:",func())
Advertisement