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

352
Visualizações
In JavaScript, is it possible to throw an error whenever any variable is set to undefined?

I find JavaScript setting a variable equal to undefined instead of throwing an error makes debugging far more difficult and I have never found it helpful. For example:

var a = ["apple","banana","orange"]
var b = a[5]

would set b to undefined instead of throwing an error. Only when b is later used would an error be thrown, making it harder to see the source of the error.

I could then check the value of b:

if(b===undefined){
throw "variable undefined"
}

but I wouldn't want to do this every time I define or change the value of any variable.

Is there any way to make JavaScript automatically throw an error whenever any variable is set to undefined?

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

Specifically for this case, and others, I have prepared a function which takes an object and arr of keys/indexes and returns the targeted value, or default in case of undefined. You can change it to throw an error.

It just means that when ever you want object value, use this syntax: gov(obj, [key1, key2]) instead of obj[key1][key2].

function gov(object, arr_keys, default_value) {
  if (!typeof arr_keys == "array") {
    throw new Error("gov arr_keys argument must be an array");
  }
  for (var i = 0; i < arr_keys.length; i++) {
    var key = arr_keys[i];
    if (typeof(key) == "number" || typeof(key) == "string") {
      if (object && (key in object)) {
        object = object[key];
      } else {
        // throw your error here.
        throw new Error("variable undefined");
        // or
        return default_value;
      }
    } else {
      throw new Error("gov key must be string or integer, " + typeof key + " given, key=" + key);
    }
  }
  return object;
}

var given = {
  property: "value",
  nested: {
    arr: [2, 4, 6]
  }
}

console.log("> when key is ok:");
console.log(given["nested"]["arr"][2])
console.log(gov(given, ["nested", "arr", 2], "default value"))

console.log("> when value is undefined:");
console.log(given["nested"]["arr"][5])
console.log(gov(given, ["nested", "arr", 5], "default 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