4

I have the following code:

<a href='#' class='link'>Click Me</a>
<script type="text/javascript">
$(".link").on('click', function(){
    event.preventDefault();
    console.log('This will appear on Chrome, but not in Firefox');
});
</script>

obviously there is an error in the code, because I dont have the 'event' variable in the function argument. Surprisingly the Chrome console will not report any error and will execute the console.log line. In case of Firefox, it will throw the following error: "ReferenceError: event is not defined" and will stop the code execution.

Why Chrome browser didn't report any error ? Are there any other exceptions in which the Chrome will ignore obviously buggy code ?

jsfiddle: https://jsfiddle.net/ArturoO/L3hym4r2/3/ Thanks in advance !

ArturoO
  • 611
  • 7
  • 19

2 Answers2

5

The reason for this is that Chrome and IE both have a global event object. This means that your code is basically using window.event instead of the missing parameter.

So the code actually is not buggy at all from Chrome's perspective. It's using the global event as intended.

There are other globals defined in some browsers and not others. These are not bugs since the host environment is allowed to create its own host objects.

1

Seems simple enough to me - it's just a difference between Chrome and Firefox. Chrome knows to have event set to undefined if there is no event running, but when the user interacts it sets it to an Event I assume. Firefox doesn't do this so when you try to run preventDefault on event, it can't, because it can't run a function on undefined.

A simple way to get around this would be to add a parameter to your function called event as an Event object is passed to any function created by $().on or .addEventListener.

Nebula
  • 6,614
  • 4
  • 20
  • 40
  • 1
    It seems that you're correct, while debuging this code in Chrome console I investigated the 'event' variable and it was set to Event object. It's only a shame that Chrome will not show any warning/notification message about this code, because programmer may think that the code is fine, but on other browser it will be broken. I curious if there any other special situations, where Chrome accepts buggy code and don't report this to the user. – ArturoO Jun 27 '15 at 11:13