2

I was trying to understand how jQuery's cross-browser events work, when I noticed these two functions in the source code:

function returnTrue() {
    return true;
}

function returnFalse() {
    return false;
}

Further down in the code these are used like:

if ( fn === false ) {
    fn = returnFalse;    <--- here
} else if ( !fn ) {
    return elem;
}

Or:

// Events bubbling up the document may have been marked as prevented
// by a handler lower down the tree; reflect the correct value.
this.isDefaultPrevented = src.defaultPrevented ||
    src.defaultPrevented === undefined &&

    // Support: Android <=2.3 only
    src.returnValue === false ?
returnTrue :    <--- here
returnFalse;    

Or:

jQuery.Event.prototype = {
    constructor: jQuery.Event,
    isDefaultPrevented: returnFalse,    <--- here
    isPropagationStopped: returnFalse,
    isImmediatePropagationStopped: returnFalse,
    isSimulated: false,

    preventDefault: function() {
        var e = this.originalEvent;

        this.isDefaultPrevented = returnTrue;    <--- here

My question is: Why one would need such functions in a dynamic language like JavaScript, where you can easily write something like below:

if ( 'function' === typeof fn ) {
    return fn.apply( this, arguments );
}

else if ( 'boolean' === typeof fn ) {
    return fn;
}

Is this a code-smell? Or are these valid practices for perhaps a cleaner-code-base with fewer conditional statements? Or is it just a narrow case where, for example, the browser expects a function to invoke which would then return a boolean value, therefore these two functions are just for saving developer's time and keystrokes?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.