0

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>

2

2 Answers 2

1

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;
Sign up to request clarification or add additional context in comments.

Comments

1
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

Still get error code. I believe that the actual errorcode is generated in this line: var generateError = numbers['badKey'][2];
@Ihor The problem lies in 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.
@Teemu Exactly... and how do I get the variable "status" to tell me that without generating error message?
You're the one who is answering here = ).

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.