Search code examples
javascriptif-statementshort-circuiting

Javascript short circuiting in if statement


I am confused about the below if statement code. Not sure what it is exactly doing

if (this.props.filterURL && nextProps.filterURL !== this.props.filterURL) {}

Can someone please help me to understand this?

Is it a short-circuiting in if statement: i.e

1- if first this.props.filterURL from left side is false then it will return false. 2- if first this.props.filterURL has a value then it will return true and the second variable nextProps.filterURL will be compared to this.props.filterURL on the right most of the statement?


Solution

  • In case of AND operator it evaluates the second expression only if the first one is true.

    In your case,

    if (this.props.filterURL && nextProps.filterURL !== this.props.filterURL) {}
    

    can be interpreted as if(expr1 && expr2) where expr1= this.props.filterURL and expr2 = nextProps.filterURL !== this.props.filterURL

    for first expression expr1 it evaluates whether it is not null or undefined...

    for the second expression expr2 nextProps.filterURL !== this.props.filterURL it checks both the value and data type. So for example if you have both value as same 1234 but for one it is of type String and for another it is for number, this condition would be true.