With variables, loops and conditionals you are already well equipped to create cool little applications.

Once you grow a certain point, however, it’s hard to keep things manageable. When you write down 100, 200, 500 lines of code, it’s all fun. But go past that number and you need a way to organize them.

Various programming languages have different ways to do so. JavaScript in particular offers one way using functions. Functions are not limited to JavaScript, of course - they are adopted into many others.

A function is a block of code with a name, which can be invoked and run when needed.

For example here’s a function:

function doSomething() {
  //code that is contained into doSomething()

Now into another part of the program you can call doSomething() and the code contained into it will execute.

Functions can accept arguments. In this way they can encapsulate a lot of functionality that the outer program does not need. If a function just needs a variable value to perform a calculation or save data to a database or communicate through the network, then that variable is all it should get from the rest of the program.

Here’s an example

function doSomething(aVariable) {
  //code that is contained into doSomething()

Functions are great because they let you abstract your code, and reuse it in other places.

You can have multiple parts of a program share a common functionality into a function, so you don’t have to maintain a similar snippet of code in multiple parts of your codebase.

Go to the next lesson