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

276
Vistas
How to check if value is undefined and if it is, set it to null
value = value ? value : null;

I want to set value to null if it is undefined. Beside what I already have written, what else I can do with less repeating and more clean?

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

0

Nullish coalescing operator (??)

You can use the nullish coalescing operator, which is a "[...] logical operator that returns its right-hand side operand when its left-hand side operand is null or undefined, and otherwise returns its left-hand side operand":

value = value ?? null;

This best fits your requirements to assign null when value is undefined. In combination with the assignment, this can be made even more concise by using the logical nullish assignment operator (??=):

value ??= null;

This should meet all your requirements, but let's also look at some possible alternatives:

Logical OR operator (||)

Another alternative could be the || operator:

value = value || null;

Or in its assignment form:

value ||= null;

The difference here is that null will be assigned for any falsy value, including 0, false, and ''.

Ternary operator (?:)

This is the original implementation from your question:

value = value ? value : null;

Essentially, this exhibits the same problem as the logical OR operator implementation in the sense that null will be assigned for any falsy value. In this case, however, this can be mitigated by including a stricter comparison in the ternary condition (making it even more verbose):

value = value != null ? value : null;
about 4 years ago · Juan Pablo Isaza Denunciar

0

undefined, null, 0, Nan and '' are considered as a falsy statement, so if you want to make sure that you update your variable only if it holds an undefined value you should consider using an if statement like this if(value==undefined) value =null;

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