Reputation: 17
I made this variable "generateError" to not work on purpose but I encounter this same issue in another context when checking for keys in an array. So my question, how do I get the variable status to just show "array not working" instead of generating error code?
var numbers = [1, 2, 3, 4];
var generateError = numbers['badKey'][2];
if (typeof(generateError)==undefined){
var status=("array not working");
}
else
{
var status=("array is working");
}
document.getElementById("status").innerHTML=status;
<div id="status"></div>
Upvotes: 0
Views: 119
Reputation: 95
Side Info - typeof method will return a string so when using it try it like this
if(typeof generateError == 'undefined')
You could make use of the try/catch methods. it will try to run everything in the try block and if theres an error the catch block will catch the error and do whatever you want with it.
var numbers = [1, 2, 3, 4];
var status;
try{
var tryToGetIndex = numbers['badKey'][2];
status = tryToGetIndex;
}
catch(error){
status="array is not working";
}
document.getElementById("status").innerHTML=status;
Upvotes: 1
Reputation: 11
var numbers = [1, 2, 3, 4];
var generateError = numbers['badKey'][2];
var status;
if (typeof(generateError)=='undefined'){
status=("array not working");
} else {
status=("array is working");
}
document.getElementById("status").innerHTML=status;
Try this and read this page its help you in future.
Upvotes: 1