Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

155
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda