3

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)

1
  • 1
    Well you will get undefined, but if you really want null.. const func = d[key] || null Commented Dec 15, 2021 at 13:50

3 Answers 3

5

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())

Sign up to request clarification or add additional context in comments.

5 Comments

Please don't modify your answer later to include others' answers.
what if Z: undefined, then all test case fail... You should use hasOwnProperty to check for existence of a property in an object
@MátéWiszt I do not see why. Your answer was wrong when I tested it so I updated mine with a working version. It was a good idea to return a function - but yours failed
@decpk the optional chaining works for undefined keys
@MátéWiszt I gave you credit now...
2

You can do:

const func = d[key] || () => null;

In this case you can call func safely.

2 Comments

That does not seem to be allowed
Yes, you will need to do (() => null)
1

It will be better to use hasOwnProperty to check wheather that property exist in the object d or not.

const d1 = {
  A: () => { return "A"; },
  B: () => { return "B"; },
  C: () => { return "C"; },
  Z: undefined,
};

const d2 = {
  A: () => { return "A"; },
  B: () => { return "B"; },
  C: () => { return "C"; },
};

const key = "Z";

function getValue(obj, key) {
  return obj.hasOwnProperty(key) ? obj[key] : null;
}

const func1 = getValue(d1, key);
console.log(func1);

const func2 = d1[key] || null;  // Shouldn't use
console.log(func2);

const func3 = d1[key] ?? null;  // Shouldn't use
console.log(func3);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.