2

I saw this line when I was reading a custom library created by a third party developers. What does this do in Javascript? Does it perform Logical OR on "modifier" and a return value from the function?

modifier = modifier || function( x ){ return x; };

KMC
  • 1,677
  • 3
  • 26
  • 55

4 Answers4

1

It returns modifier, if it has a truthy value, like function. Otherwise it returns a function without calling it.

Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
1

Yes. In JavaScript, the || returns the left if it is a truthy value or the right if the left is a falsy value.

Effectively, if modifier is already a function, it will just leave it set. If it is undefined or null, it will set a reference to the right side function. It will not evaluate the function, however.

It would look like this if evaluated.

modifier = modifier || function( x ){ return x; }(); // notice the method invocation
MPavlak
  • 2,133
  • 1
  • 23
  • 38
1

The || operator is a lazy one. If it has the means necessary to compute it's value it doesn't evaluate the rest of the expression. The value of the logical operation OR is true when one of the parameters is true, so if modifier is considered to be a true value it will return itself and when not it returns the second parameter.

To see what is considered true in JS check here.

Adrian Jałoszewski
  • 1,695
  • 3
  • 17
  • 33
1

Yes.
More in detail, it checks if modifier evaluates to true; in this case it assigns modifier value to modifier variable (noop); otherwise it assigns an anonymous function to modifier.

MarcoS
  • 17,323
  • 24
  • 96
  • 174
  • No - based on the question, he's asking if it's an OR of the RETURN value from the function. It is OR'ed with the function itself. While your explanation is correct, the answer's first line should be "No." I would expand "it checks if modifier evaluates to true" to "it checks if modifier evaluates to a truthy value (and a function definition evaluates to truthy so if modifier is already a function, it returns that function)" – MPavlak Sep 29 '16 at 17:37