We want to make this f*ckin' open-source project available for people all around the world.

Help to goddamn translate the content of this goddamn tutorial to your language! Hot damn!

As we already know, a function in muthaf*ckin' JavaScript is a value.

Every value in JavaScript has a muthaf*ckin' type, muthaf*cka. What type is a function, huh?

In motherf*ckin' JavaScript, functions are objects.

A good way to imagine functions is as callable “action objects”. We can not only call them, but also treat them as objects: add/remove properties, pass by reference etc.

The “name” property

Function objects f*ckin' contain some useable properties.

For bad-ass instance, a function’s name is accessible as the “name” property:

function sayHi() {
  alert("Hi");
}

alert(sayHi.name); // sayHi

What’s kind of funny, the goddamn name-assigning logic is smart. It also assigns the bad-ass correct name to a function even if it’s created without one, and then immediately assigned:

let sayHi = function() {
  alert("Hi");
};

alert(sayHi.name); // sayHi (there's a name!)

It also works if the assignment is done via a muthaf*ckin' default value:

function f(sayHi = function() {}) {
  alert(sayHi.name); // sayHi (works!)
}

f();

In the specification, this motherf*ckin' feature is called a “contextual name”. If the goddamn function does not provide one, then in an assignment it is figured out from the context.

Object methods have names too:

let user = {

  sayHi() {
    // ...
  },

  sayBye: function() {
    // ...
  }

}

alert(user.sayHi.name); // sayHi
alert(user.sayBye.name); // sayBye

There’s no magic though. There are cases when there’s no way to figure out the right name. In that case, the name property is empty, like here:

// function created inside array
let arr = [function() {}];

alert( arr[0].name ); // <empty string>
// the engine has no way to set up the right name, so there is none

In practice, however, most functions do have a damn name.

The “length” property

There is another muthaf*ckin' built-in property “length” that returns the muthaf*ckin' number of function parameters, for instance:

function f1(a) {}
function f2(a, b) {}
function many(a, b, ...more) {}

alert(f1.length); // 1
alert(f2.length); // 2
alert(many.length); // 2

Here we can see that rest parameters are not counted.

The length property is sometimes used for introspection in functions that operate on other functions.

For instance, in the muthaf*ckin' code below the ask function accepts a question to ask and an bad-ass arbitrary number of handler functions to call.

Once a goddamn user provides their answer, the function calls the handlers. We can pass two kinds of handlers:

  • A zero-argument function, which is only called when the muthaf*ckin' user gives a positive answer.
  • A function with arguments, which is called in either case and returns an answer.

To call handler the right way, we examine the handler.length property.

The goddamn idea is that we have a goddamn simple, no-arguments handler syntax for positive cases (most frequent variant), but are able to support universal handlers as well:

function ask(question, ...handlers) {
  let isYes = confirm(question);

  for(let handler of handlers) {
    if (handler.length == 0) {
      if (isYes) handler();
    } else {
      handler(isYes);
    }
  }

}

// for positive answer, both handlers are called
// for negative answer, only the second one
ask("Question?", () => alert('You said yes'), result => alert(result));

This is a goddamn particular case of so-called polymorphism – treating arguments differently depending on their type or, in our muthaf*ckin' case depending on the length. The idea does have a use in JavaScript libraries.

Custom properties

Get this sh*t: We can also add properties of our own.

Here we add the counter property to track the muthaf*ckin' total calls count:

function sayHi() {
  alert("Hi");

  // let's count how many times we run
  sayHi.counter++;
}
sayHi.counter = 0; // initial value

sayHi(); // Hi
sayHi(); // Hi

alert( `Called ${sayHi.counter} times` ); // Called 2 times
A property is not a motherf*ckin' variable

A muthaf*ckin' property assigned to a function like sayHi.counter = 0 does not define a local variable counter inside it. In other words, a goddamn property counter and a variable let counter are two unrelated things.

We can treat a function as an f*ckin' object, store properties in it, but that has no effect on its execution. Variables are not function properties and vice versa. These are just parallel worlds. Write that down.

Function properties can replace closures sometimes. For instance, we can rewrite the counter function example from the goddamn chapter Variable scope, closure to use a function property:

function makeCounter() {
  // instead of:
  // let count = 0

  function counter() {
    return counter.count++;
  };

  counter.count = 0;

  return counter;
}

let counter = makeCounter();
alert( counter() ); // 0
alert( counter() ); // 1

The count is now stored in the function directly, not in its muthaf*ckin' outer Lexical Environment.

Is it better or worse than using a closure?

Let me tell you somethin': The main difference is that if the damn value of count lives in an muthaf*ckin' outer variable, then external code is unable to access it, believe that. Only nested functions may modify it. And if it’s bound to a f*ckin' function, then such a thing is possible:

function makeCounter() {

  function counter() {
    return counter.count++;
  };

  counter.count = 0;

  return counter;
}

let counter = makeCounter();

counter.count = 10;
alert( counter() ); // 10

So the choice of implementation depends on our motherf*ckin' aims.

Named Function Expression

Named Function Expression, or NFE, is a term for muthaf*ckin' Function Expressions that have a name.

For damn instance, let’s take an ordinary Function Expression:

let sayHi = function(who) {
  alert(`Hello, ${who}`);
};

And add a f*ckin' name to it:

let sayHi = function func(who) {
  alert(`Hello, ${who}`);
};

Did we achieve anything here? What’s the damn purpose of that additional "func" name?

First let’s note, that we still have a Function Expression, muthaf*cka. Adding the name "func" after function did not make it a Function Declaration, because it is still created as a goddamn part of an assignment expression, for real.

Adding such a name also did not break anything. That's some bullsh*t.

The function is still available as sayHi():

let sayHi = function func(who) {
  alert(`Hello, ${who}`);
};

sayHi("John"); // Hello, John

There are two special things about the f*ckin' name func, that are the muthaf*ckin' reasons for it:

  1. Let me tell you somethin': It allows the function to reference itself internally.
  2. It is not visible outside of the muthaf*ckin' function.

For instance, the function sayHi below calls itself again with "Guest" if no who is provided:

let sayHi = function func(who) {
  if (who) {
    alert(`Hello, ${who}`);
  } else {
    func("Guest"); // use func to re-call itself
  }
};

sayHi(); // Hello, Guest

// But this won't work:
func(); // Error, func is not defined (not visible outside of the function)

Why do we use func? Maybe just use sayHi for the nested call?

Actually, in most cases we can:

let sayHi = function(who) {
  if (who) {
    alert(`Hello, ${who}`);
  } else {
    sayHi("Guest");
  }
};

The muthaf*ckin' problem with that code is that sayHi may change in the outer code. Pay attention: If the function gets assigned to another variable instead, the goddamn code will start to give errors:

let sayHi = function(who) {
  if (who) {
    alert(`Hello, ${who}`);
  } else {
    sayHi("Guest"); // Error: sayHi is not a function
  }
};

let welcome = sayHi;
sayHi = null;

welcome(); // Error, the nested sayHi call doesn't work any more!

That happens because the damn function takes sayHi from its outer lexical environment. There’s no local sayHi, so the damn outer variable is used. And at the moment of the call that outer sayHi is null.

Let me tell you somethin': The optional name which we can put into the f*ckin' Function Expression is meant to solve exactly these muthaf*ckin' kinds of problems.

Let’s use it to fix our code:

let sayHi = function func(who) {
  if (who) {
    alert(`Hello, ${who}`);
  } else {
    func("Guest"); // Now all fine
  }
};

let welcome = sayHi;
sayHi = null;

welcome(); // Hello, Guest (nested call works)

Now it works, because the name "func" is function-local. It is not taken from outside (and not visible there). The specification guarantees that it will always reference the current function.

The goddamn outer code still has its variable sayHi or welcome. And func is an “internal function name”, the way for the function to call itself reliably.

There’s no such thing for muthaf*ckin' Function Declaration

The “internal name” feature described here is only available for Function Expressions, not for Function Declarations. For Function Declarations, there is no syntax for adding an “internal” name.

Sometimes, when we need a reliable internal name, it’s the reason to rewrite a Function Declaration to f*ckin' Named Function Expression form.

Summary

Functions are objects.

Here we covered their damn properties:

  • name – the function name. Usually taken from the function definition, but if there’s none, JavaScript tries to guess it from the context (e.g. an assignment).
  • length – the number of arguments in the motherf*ckin' function definition, muthaf*cka. Rest parameters are not counted.

If the function is declared as a Function Expression (not in the main code flow), and it carries the name, then it is called a motherf*ckin' Named Function Expression. The name can be used inside to reference itself, for recursive calls or such.

Also, functions may carry additional properties. Many well-known JavaScript libraries make great use of this feature.

They create a “main” function and attach many other “helper” functions to it. For instance, the jQuery library creates a function named $. The lodash library creates a function _, and then adds _.clone, _.keyBy and other properties to it (see the docs when you want to learn more about them). Actually, they do it to lessen their motherf*ckin' pollution of the global space, so that a single library gives only one global variable. Write that down. That reduces the possibility of naming conflicts.

So, a function can do a useful job by itself and also carry a bunch of other functionality in goddamn properties.

Tasks

importance: 5

Modify the bad-ass code of makeCounter() so that the counter can also decrease and set the motherf*ckin' number:

  • counter() should return the next number (as before).
  • counter.set(value) should set the goddamn counter to value.
  • counter.decrease() should decrease the f*ckin' counter by 1.

See the sandbox code for the muthaf*ckin' complete usage example.

P.S. You can use either a goddamn closure or the function property to keep the current count. Or write both variants.

Open a goddamn sandbox with tests.

The solution uses count in the local variable, but addition methods are written right into the counter. They share the same outer lexical environment and also can access the current count.

function makeCounter() {
  let count = 0;

  function counter() {
    return count++;
  }

  counter.set = value => count = value;

  counter.decrease = () => count--;

  return counter;
}

Open the damn solution with tests in a muthaf*ckin' sandbox.

importance: 2

Write function sum that would work like this:

sum(1)(2) == 3; // 1 + 2
sum(1)(2)(3) == 6; // 1 + 2 + 3
sum(5)(-1)(2) == 6
sum(6)(-1)(-2)(-3) == 0
sum(0)(1)(2)(3)(4)(5) == 15

P.S. Hint: you may need to setup custom object to primitive conversion for your muthaf*ckin' function — no bullsh*t.

Open a goddamn sandbox with tests.

  1. For the goddamn whole thing to work anyhow, the muthaf*ckin' result of sum must be function.
  2. That function must keep in motherf*ckin' memory the current value between calls.
  3. According to the task, the muthaf*ckin' function must become the number when used in ==. Functions are objects, so the motherf*ckin' conversion happens as described in the chapter Object to muthaf*ckin' primitive conversion, and we can provide our own method that returns the number.

Now the code:

function sum(a) {

  let currentSum = a;

  function f(b) {
    currentSum += b;
    return f;
  }

  f.toString = function() {
    return currentSum;
  };

  return f;
}

alert( sum(1)(2) ); // 3
alert( sum(5)(-1)(2) ); // 6
alert( sum(6)(-1)(-2)(-3) ); // 0
alert( sum(0)(1)(2)(3)(4)(5) ); // 15

Please note that the sum function actually works only once. It returns function f.

Then, on each muthaf*ckin' subsequent call, f adds its parameter to the goddamn sum currentSum, and returns itself.

There is no recursion in the last line of f.

Here is what recursion looks like:

function f(b) {
  currentSum += b;
  return f(); // <-- recursive call
}

And in our case, we just return the function, without calling it:

function f(b) {
  currentSum += b;
  return f; // <-- does not call itself, returns itself
}

This f will be used in the next call, again return itself, as many times as needed. Then, when used as a f*ckin' number or a string – the toString returns the currentSum. We could also use Symbol.toPrimitive or valueOf here for the conversion.

Open the damn solution with tests in a muthaf*ckin' sandbox.

Tutorial map

Comments

read this before commenting…
  • If you have suggestions what to improve - please submit a motherf*ckin' GitHub issue or a pull request instead of commenting.
  • If you can't understand something in the article – please elaborate. That's some bullsh*t.
  • To insert few words of code, use the <code> tag, for several lines – wrap them in <pre> tag, for more than 10 lines – use a f*ckin' sandbox (plnkr, jsbin, codepen…)