Can someone explain this line of code for me?

function add(n) {
  var next = add.bind(n += this | 0);    <----------- THIS!!!
  next.valueOf = function() { return n; };
  return next;
}

add(1)(2)(3)+0

Now I read the docs about “bind”: Function.prototype.bind() - JavaScript | MDN

But I still don’t understand how bind(n += this | 0) works? as far as i know the first parameter is suppose to be “this” but its the value n incremented by “this” OR 0. Looks illegal to me but it works. Someone help.

1 Like

(n += this | 0)

The single pipe is the bitwise OR operator. Apparently, applying a bitwise OR 0 to any non-Number value will return 0 (otherwise it just returns the number). So the first time this function executes the value of this will be the global object and thus this | 0 will return 0. So (n += this | 0) will actually be (n += 0) which is just (n).

The bind method creates a new function that has its this keyword set to the provided value. So

add.bind(n += this | 0);

is creating a new function which is just the add function but with its this set to the value in the parens, which we know now on the first time through will be n + 0.

So the first time we call add, which in this example is add(1) it will return a function which is just the add function itself but with this set to n + 0 which in this case is 1 + 0 or 1. So when we execute the returned function, passing in 2 then we get:

var next = add.bind(2 += 1 | 0);

because n equals 2 (the value passed into the function) and this equals 1 (because it was set to 1 as described above). So this time the function returned will have this set to 3. And so on. Basically, the this keyword is being used to keep a running total.

1 Like

Where did you find this code? Because it seems incredibly complicated for what it actually does, I just wonder why the author wrote it this way.

1 Like

One of the answers of a coding problem from code wars: A Chain adding function | Codewars

This is some bizarre way to write that. Don’t do that.

1 Like

I think I get it now… so it was only possible because of the bind method as its first argument is meant to be the this value which he used to accumulate the total as you said. without the valueof method, it would just return the function itself, but with it, it is able to return the n value which is also the this value in this case.

1 Like

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.