Chapter 2: Functions

Functions are perhaps the most important member in Javascript. Functions are so called "first class citizens" in Javascript. They can be assigned to variables and passed around. We'll go into functions even further in the next chapters about scope and closures.

You may use either method, but I suggest the anonymous function (because of confusion that may lead to hoisting of named functions). In Javascript you can assign functions to variables. You can even pass functions as parameter in another function. This is useful when making callback functions.

It might look a little silly, but this trick is very useful for scope changes. More on scopes next chapter!

Pass by value or pass by reference?

When you pass a var into a function, it's important to remember whether the variable is a value or a reference. The difference is that pass by value means the variable is copied/cloned, whereas pass by reference means the original variable can be accessed. In Javascript it works as following:

Booleans, Numbers and Strings are passed by value. Everything else is passed by reference.

In the above example, we can clearly see that var string and var number aren't changed after calling doStuff. The variables str and num were local to the function and didn't change the original string and number. This didn't apply to cat, which was changed after doStuff.

So remember that everything except Number and String are references to the original variables. It's very easy to accidentally change an object that you didn't intend to.