Question

I came across this piece of JS code on a minified library that is puzzling me:

...
return e.input || L(), e.addTest = function(a, b) {
...

I played with it on a jsFiddle without much luck understanding what is happening.

I would like to know:

  1. when does it return? always apparently.
  2. what does it return? on my test it returns undefined... why?
  3. when is the code L() executed? Only if e.input returns false?
  4. when is e.addTest set? according to my test always... why?
Was it helpful?

Solution

1. when does it return?
always.

2. what does it return? on my test it returns indefined... why?
if you alert alert it alerts undefined

3. when is the code L() executed?
if e.input returns false

4. when is e.addTest set?
The comma operator evaluates both of its operands (from left to right) and returns the value of the second operand.

This is the unminified code in your case:

if (e.input){
    L();
}
e.addTest = function(a, b) {};
return e.addTest;

OTHER TIPS

Assuming your code looks like this:

return e.input || L(), e.addTest = function(a, b) {
    ...
}

This code will:

  1. Evaluate e.input || L()
    • This means that L will run if e.input is not falsy (undefined, 0, false, null, empty string)
  2. Evaluate e.addTest = function(a, b) { ... }
    • This stores a new function in e.addTest
    • Then, yields that function for the whole expression, so that function is returned

You can think of this as:

return ( ( e.input || L() ), e.addTest = function() { ... } )

where the || operation is done first, followed by the assignment operation.

This is because:

  • The || operator is short-circuting, and will yield its first non-falsy operand
    • So return a || b returns a if a is truthy or otherwise returns b
  • The , operator evaluates both operands to the left and right, but then yields the right operand
    • So return a(), b() runs both a() and b() but returns the result of b()
  • The assignment operation yields the value assigned
    • So return a = 5 will store 5 in a and then return 5

In your case, you see undefined because the return value of alert is always undefined.

Your code is entirely incomplete..

For help with minified code you can use this site, they turn minified code into expanded code that's significantly easier to read.

I think it means that if e is undefined or false, then return L(), otherwise return e.addTest (where e.addTest is defined as follows).

ETA: just saw your edits. A1rPun explains it well.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top