3

What does this JavaScript snippet mean? The (evt) part is so confusing; evt is not a boolean. How it works?

function checkIt(evt) {
        evt = (evt) ? evt : window.event
        var charCode = (evt.which) ? evt.which : evt.keyCode
        
    }
Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
amesh
  • 1,311
  • 3
  • 21
  • 51

4 Answers4

9

evt = (evt) ? evt : window.event is just the inline if syntax. It's equivalent to this code:

if (evt) {
    evt = evt;
} else {
    evt = window.event;
}

If evt is truthy, evt will be left alone. If evt isn't truthy, it will be replaced with window.event.

Blender
  • 289,723
  • 53
  • 439
  • 496
  • 1
    @amesh: Right, that's why I said *truthy*. If `evt` isn't `null`, `undefined`, `NaN` (I think), `0` or `false`, it's considered truthy. Basically, if `evt` has been set already, it's truthy. – Blender Sep 28 '12 at 07:07
3

It's for event listeners.

IE6-IE8 used a totally different event method than the W3C standard.

When an event fires, a W3C-standard browser will pass an event object in the callback:

function keyPressed (e) { /* do stuff with e */ }

In your case, it's keydown (or something else using keyCode).
IE didn't support this, instead it had window.event which was updated every time an event happened.

So your function is checking to see if an object was passed into it:

evt = (evt) ? evt : window.event;
// does `evt` exist, and is it anything but '', 0, false, null, undefined, NaN
// yes: evt = itself (W3C)
// no: evt = window.event (IE6-8)

Then the code asks if evt.which exists, to try to figure out where to get the keyCode from. evt.keyCode is what you should be using for modern browsers, in the case of keydown and keyup.

Norguard
  • 26,167
  • 5
  • 41
  • 49
1

Assignment expressions like that are evaluated from right to left, so this means:

  • if evt has a truthy value, assign this value back to evt
  • if not, assign the value of window.event regardless of its content to evt
jAndy
  • 231,737
  • 57
  • 305
  • 359
1

It means: if the evt parameter has a value then keep the value, if it doesn't have a value then use window.event instead.

The ? and ':' symbols are part of the ternary if operator:

var w = x ? y : z;

so above you assign either y or z to w depending on whether x is considered to be a true or false value.

If the checkIt function was called without passing in an evt argument i.e. checkIt() then inside the function the evt variable will have the value of undefined which is treated as false within an if condition.

codebox
  • 19,927
  • 9
  • 63
  • 81