Hypothetically - let's say I have some JavaScript to handle the clicks of three different buttons:
$("#working").click(function () {
alert("Seth Rollins is the greatest champion of all time.");
console.log("WWE World Heavyweight Champion");
});
$("#fix-this-error").click(function () {
alert(this_should_not_show_up_in_the_console);
console.log("This won't show");
});
$("#should-error").click(function () {
alert(oipewavqn2389tvb3t8ahwleuhtvab3iwuthabvlewiuweaqhaoiuhva98r3b2);
console.log("This won't show either");
});
The first one will work as it alerts a string, and it will log to the console the message that is written after the alert.
The second and third functions will not work because they are trying to alert variables that are not defined. Their subsequent console.logs
will not output anything.
My Question: Is it possible to prevent the error from the second function from outputting to the console while maintaining the following properties?:
console.log
still should not executeEdit: Here is a fiddle to play around in - https://jsfiddle.net/5m40LLmm/2/
SUPER EDIT: I don't want the execution of logic in the second function to really change. I want the error to be thrown, and the .click()
handler should exit before it reaches console.log as it does now. I just want to prevent the error from being shown. I don't want to use try
and catch
to circumvent the error or to somehow check if the variable exists before I use alert()
. I know and want the error to happen, I just want to prevent its display. I hope that makes this more clear.
Use try catch
$("#fix-this-error").click(function () {
try {
alert(this_should_not_show_up_in_the_console);
console.log("This won't show");
} catch() {}
});
or check to see if the variable is defined before you try to use it.