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>
-
2just use optional chaining: numbers['badKey']?.[2]n--– n--2021年03月05日 12:04:59 +00:00Commented Mar 5, 2021 at 12:04
-
Oops, I linked to a wrong page, should have been developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…Teemu– Teemu2021年03月05日 12:09:32 +00:00Commented Mar 5, 2021 at 12:09
2 Answers 2
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;
Comments
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.
4 Comments
numbers['badKey'][2] where retrieving index 2 from ['badKey'] fires an error. OP doesn't want an error message, they want to continue the execution.