Search code examples
reactjsreact-props

What does this code snipe do or is it just a mistake


I learn Reactjs and read lots of code and cant make this out.
Is this a mistake in the code or does it do something;

I mean this line:

this.props.onEnd && this.props.onEnd();

I know the onEnd() is a callback to parent but how does it work looking like this? Code;

/**
 *  Let parent components know that we reached the end of display
 */
_onEnd(isVisible) {
    if (!isVisible) return;
    this.props.onEnd && this.props.onEnd();
}

Solution

  • It's equivalent to saying this:

    if (this.props.onEnd != null) {   // validate not null or undefined
        this.props.onEnd();           // execute function
    }
    

    When expressed as follows:

    this.props.onEnd && this.props.onEnd();
    

    The expression will short circuit if onEnd is null or undefined. If it is, then the expression evaluates logically as:

    false && this.props.onEnd()
    

    In which case since false && <anything else> will always evaluate to false. The runtime won't evaluate the call on the right if the left of the and operator evaluates to false.

    Similarly, if onEnd is valid, then it logically gets evaluated as:

    true && this.props.onEnd()
    

    In which case, this.props.onEnd() is evaluated and executed.

    For more information, look up up boolean short circuit as an internet search.