What does the following mean in JavaScript?
var evt=event||window.event;
'evt' is intended to be a replacement for 'events' . It enables and encourages functional programming and makes heavy use of typescript's type inference features to provide type safety while keeping things concise and elegant 🍸 . Suitable for any JS runtime env (deno, node, old browsers, react-native ...)
Deprecated: This feature is no longer recommended.
JavaScript Window Events are associated with the windows object defined for describing the events. There are other ways also which can handle the windows event like using and defining within the body tag for the events but that makes the entire code and the event a bit cumbersome to understand and evaluate.
It means that the variable evt
is assigned to the value of event
or if event
is undefined it is assigned the value of window.event
.
How this works is that in javascript, boolean operators don't evaluate to true or false but instead evaluates to the value of the last object that is not falsy* or the falsy value.
So the statement first evaluates the expression event || window.event
. If event
is true then the expression does not need to be evaluated any further since an OR only needs one member to be true. Therefore the value of event
is returned. If event
is falsy then the the right side of the OR operator needs to be evaluated to determine if the result is false. In which case, if window.event
is not falsy then its value is returned.
This is a very common idiom to get the event object from event handlers. On standards compliant browsers, the event object is passed as the first parameter to the event handler. But on IE the event object is a global variable. And for historical reasons, all global variables are members of the window object.
So the code should look something like this:
element.onclick = function (event) {
var evt = event || // use the value of event if available or
window.event;// if not assume it's IE and use window.event
/* ... */
}
Note: * falsy values in javascript are: false, 0, null and undefined.
The code is a hack because Microsoft decided to put their events in the global window.event
instead of passing it as a parameter to the event function.
So, this code will attempt to set evt
to the event passed in (which will work for the non-Microsoft browsers) and, if that turns out to be null
(as it will be for Microsoft browsers), it will then grab it from the global.
From that point on, your function can just use evt
disregarding browser differences (well, at least those relating to events).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With