So I have an if statement, and I want it so that if the condition is true, an error is thrown. It’s a form for users to remove items from an array called myArr, and if that item does not exist in myArr I want it to throw an error.
$('#remove_user').submit(function(){
id = $('#user_num').val();
diffVal = $.grep(myArr, function(value, i){
return value != id;
});
if (diffVal.length == myArr.length) {
//I want the error here to say "Does not exist."
} else {
myArr = diffVal
};
$('#user_list').html('');
for (var i=0; i < myArr.length; i += 1) {
$('#user_list').append('<li>' +myArr[i]+ '</li>');
};
return false;
});
You can use
throw "Item does not exist!"But I’ve found that it’s better to throw an
Errorobject, like so:throw new Error("Item does not exist!");If you throw an
Erroryou get marginally better tracibility. Error handling in JavaScript is sadly still abysmal.