Functions

In stead of writing code that does the same thing several places in our code, or for that matter, as a way to write code that is easily maintainable, we should have a look at functions.

Functions are pieces of code wrapped inside a variable, it can do a certain task and be called multiple times from several places in the program. In JavaScript functions are variables that happen to have a function, rather than being one specific value. Functions can be written in two equal ways. Which one you choose is purely a personal preference.

var square = function(x){
    return x * x
}

function square(x){
    return x * x
}

You call (or invoke) the function by writing it's name, followed by parentheses (unlike variables, where you do not use parentheses), and, if required by the function, the arguments.

When talking about functions, two words are easy to confuse: parameters and arguments. In the example above, the x within the parentheses is called a parameter. Parameters are variables that the function require. When calling upon a function that have parameters in it's function declaration (as in the example above), you pass along an argument, that is the variable that you send to the function.

// x is the parameter
function square(x){
    return x * x
}

// 5 is the argument
console.log(square(5))

>> 25

In the example above, the argument is passed to the function, then the result is returned. The keyword return tells the function to return following value. In this case we call the function square from within a console.log() function. It is possible to also have the print function within our square function, which would yield a similar result. However, by using the return statement, we can later use the result, rather than just print it.

A function doesn't need parameters, but it can take any number of parameters if needed. A good practice is to create functions that only return a value, and does not change anything outside it's scope. That way your code is easier to read, maintain and debug.

var five = 5

function changeAVariable(){
    five = 6
}

console.log(five)

>> 5

changeAVariable()
console.log(five)

>> 6

If your functions grow into large blocks of code, or you find yourself writing the same code over and over again, structuring your code into several functions is a good idea.

Last updated