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;

The Beast
  • 1
  • 1
  • 2
  • 24
MBK
  • 525
  • 1
  • 8
  • 23
  • 1
    Something to note is that null is falsy. – Iman K Dec 03 '15 at 02:45
  • 1
    The best explanation can be found here: http://stackoverflow.com/questions/2802055/what-does-the-construct-x-x-y-mean – Marc Young Dec 03 '15 at 02:46
  • 1
    Or here http://stackoverflow.com/a/4576915/3791314 because it explains truthy/falsy values – mark Dec 03 '15 at 02:51
  • JavaScript's OR operator doesn't return boolean true/false values like other languages. Rather it checks if the left evaluates to true when type casted to boolean, If true, it returns the value rather than a boolean. If false, then it returns the second value regardless of its value. Thus in JavaScript, the following two statements are equivalent: `$result=$value1||$value2;` `$result=$value1?$value1:$value2;` the weakness with the `?:` syntax is we need to dedicate a statement for assigning the value which isn't possible in the midst of another statement, thus `||` can be very powerful. – Ultimater Dec 03 '15 at 02:57

4 Answers4

2

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.

Hunan Rostomyan
  • 2,176
  • 2
  • 22
  • 31
1

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.

shenkwen
  • 3,536
  • 5
  • 45
  • 85
1

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.

Fawzan
  • 4,738
  • 8
  • 41
  • 85
-5

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
 }
Jake Psimos
  • 640
  • 3
  • 10