Search code examples
javascriptdom-events

Meaning of evt = (evt) ? evt : window.event


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
        
    }

Solution

  • 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.