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

350
Vistas
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 Respuestas
Responde la pregunta

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