Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

357
Vistas
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)

about 4 years ago · Juan Pablo Isaza
3 Respuestas
Responde la pregunta

0

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

about 4 years ago · Juan Pablo Isaza Denunciar

0

You can do:

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

In this case you can call func safely.

about 4 years ago · Juan Pablo Isaza Denunciar

0

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

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda