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?
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"))