Please also describe that why this statement is executing that way.
I'm confused because < operator has higher precedence in the statement below. After execution of the x > 0 the execution should go for && operator but it is not executing. So I'm confused about what the execution order is and why it is executing in that way.
Thanks for your time!
The code is following:
let x = 1;
x > 0 || alert() && "hii"
If you take a look at the operators precedence.
> has a highest priority&& is the next one by priority|| is the next one by prioritySo expression is executed like:
(x > 0) || (alert() && "hii")
In this case x > 0 is true. Because JavaScript || short-circuits if the first operand is truthy, the second operand will not be evaluated.
Its like:
fun1() || func2()
If the return value of fun1() is truthy, than func2() will not be executed at all.
There is no need to use the right side of the || because the left side is already truthy, so no matter what the right side would be, it couldn't change the outcome anyway (both true || true and true || false would evaluate to true). Therefore, nothing other than x > 0 needs to be evaluated to get an unambiguous result, alert() && "hii" is skipped and the return value is true (the result of x > 0). (This is called short-circuiting or conditional evaluation.) See docs.
If you tried this :
let x = 1;
x > 0 || alert() && false
The output would be true, this is because && is executed before the || operator, "hii" is evaluated as true so this what confused you to think that there is something wrong, as ( true || alert() && true will give the same result as true || (alert() && true).