Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

347
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!