I found this code in JavaScript tutorial. It reads if value is null the this.current is assigned to 0, otherwise to a value. How does it work?
I am confused because there is no null
or ?? operator in the code.
this.current=value||0;
I found this code in JavaScript tutorial. It reads if value is null the this.current is assigned to 0, otherwise to a value. How does it work?
I am confused because there is no null
or ?? operator in the code.
this.current=value||0;
Well, the semantics of the ||
(logical or) operator is such that as soon as its left side is truthy, it short-circuits and returns that value, otherwise it returns what's on the right side.
That common pattern takes advantage of the semantics by passing a possibly falsy (x) value and a default (y) to the operator: x || y
. If x turns out to be non-falsy, that whole expression evaluates to x
, otherwise y
.
Null
is not mentioned there, because null
is falsy and the pattern works for all falsy values.
This is how operator ||
in javascript work. Instead of returning a boolean value, it returns either operand depending on whether they are true or not.
If the first operand is a "true" value, it returns its value directly without even looking at the other operand, else it just returns the other operand's value.
It is simple, On the right side you have value || 0
That evaluates to the this.current
. What you need to understand is the right side evaluates the boolean OR
first. That is how JS ||
supposed to work. It return the value instead of TRUE/FALSE
if they are not boolean.
If you compare something using === it will compare the value and type. For example
var a = false;
If(a == null){
//triggered
}
If(a === null){
//not works
}