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

152
Vistas
How I can skip variable if undefined in javascript

i trying to get some data json from my api, But I faced this problem:

enter image description here

Code javascript to get json data from my API :

// Get Specs 
    $.getJSON('https://my_api' , function(specs) {
    console.log(specs);
  
    $.each(specs, function(index, vsp) {
    console.log(vsp);

    var in = vsp.specs[0].value;
    var ch = vsp.specs[1].value;
    var ra = vsp.specs[2].value;
    var ca = vsp.specs[3].value;
    var ba = vsp.specs[4].value;

JSON data Ex:1 :

"specs": [
        {
         "value": "info1"
      },
      {
         "value": "info2"
      },
      {
         "value": "info3"
      },
      {
         "value": "infp4"
      },
      {
         "value": "info5"
      }
   ]

JSON data Ex:2 :

"specs": [
        {
         "value": "info1"
      },
      {
         "value": "info2"
      },
      {
         "value": "info3"
      },
      {
         "value": "infp4"
      }
   ]

For the first example, everything works fine, but for the second example i'm having this problem :

Cannot read properties of undefined (reading 'value')
var ba = vsp.specs[4].value; ==> value is undefined 

How i can skip this var if is undefined ? Any help would appreciate it.

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

0

you can just insert a ? between the property name and the period between the next property.

var ba = vsp?.specs?.[4]?.value;

also you can use the Nullish coalescing operator :

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Nullish_coalescing_operator

about 4 years ago · Juan Pablo Isaza Denunciar

0

You can use the optional chaining (?.) operator.

According to MDN:

The optional chaining operator (?.) enables you to read the value of a property located deep within a chain of connected objects without having to check that each reference in the chain is valid.

This operator can be helpful in your use case.


To use it, simply use the code below.

var ba = vsp.specs[4]?.value;

This will, instead of throwing an error if it can't find the value property, return undefined.


This should help with the error. However, you should still add a check for if the variable is undefined. You can use something like below.

ba = ba ?? "Fallback";

This will use the left-hand side value (ba) unless it is null or undefined, in which case will use the right-hand side value ("Fallback").

An if statement can do something similar.

if (typeof ba === "undefined" || ba === null) {
  ba = "Fallback";
}

The reason you can't use ! is because it will evaluate anything of a falsy value to be false. This will only fallback if it is undefined or null.

about 4 years ago · Juan Pablo Isaza Denunciar

0

in the json2 it's impossible to get vsp.specs[4] because only have positions from 0 to 3 in the array, could ask for the position in the array exists something like

var ba = (4<vsp.length) ? vsp.specs[4].value:null;

or

var ba = vsp?.specs?.[4]?.value;
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