8

I am banging my head trying to find the error in this code. I have checked it so many times can someone point out where the problem is?

$(function() {
  try {
    function endswith(str, ends) {
      if (ends === '') return true;
      if (str == null || ends == null) return false;
      str = String(str);
      ends = String(ends);
      return str.length >= ends.length && str.slice(str.length - ends.length) === ends;
    }
    var referrer = new URL(document.referrer).domain;
    if (endswith(referrer, "xyz.com")) {
      $(".logo .logo-external").remove();
    } else {
      $(".logo .logo-internal").remove();
    }
  } catch () {}
});
Barmar
  • 669,327
  • 51
  • 454
  • 560
Imo
  • 1,457
  • 3
  • 26
  • 51
  • You need a variable name inside the `catch()` parentheses. – Barmar Aug 18 '15 at 19:56
  • Also see: [Can I use a try/catch in JavaScript without specifying the catch argument/identifier?](https://stackoverflow.com/questions/21624456/can-i-use-a-try-catch-in-javascript-without-specifying-the-catch-argument-identi/56001361) – sleske Jun 14 '21 at 08:42

2 Answers2

13

catch (e) {} You missed the variable e

$(function() {
  try {
    function endswith(str, ends) {
      if (ends === '') return true;
      if (str == null || ends == null) return false;
      str = String(str);
      ends = String(ends);
      return str.length >= ends.length && str.slice(str.length - ends.length) === ends;
    }
    var referrer = new URL(document.referrer).domain;
    if (endswith(referrer, "xyz.com")) {
      $(".logo .logo-external").remove();
    } else {
      $(".logo .logo-internal").remove();
    }
  } catch (e) {}
});
joyBlanks
  • 6,066
  • 1
  • 19
  • 44
0

As per MDN, try...catch syntax is defined similar to the following:

try {
   try_statements
}
...
[catch (exception_var) {
   catch_statements
}]
[finally {
   finally_statements
}]

This means the exception_var is NOT optional. Otherwise, it would look like this:

...
[catch ([exception_var]) {     // Uncaught SyntaxError: Unexpected token )
   catch_statements
}]
...
themefield
  • 3,120
  • 27
  • 32