JavaScript

All about functions in JavaScript

Published on 

Functions are one of the most important programming concepts to understand. But what is a function, and how do we use it?

Functions allow us to create reusable code that we can use to either perform various tasks or computations. We can also write functions that take in an input via parameters and then use those values to produce an output.

For example, say you wanted to uppercase two variables.

const person = 'john Smith';
const city = 'new York';

You would need to write the same logic twice to get your desired result

const uppercasePerson = person[0].toUpperCase() + person.slice(1); // -> 'John Smith'
const uppercaseCity = city[0].toUpperCase() + city.slice(1); // -> 'New York'

Even in this small example, it is quite time consuming to write the same code and it's easy to mess something up.

A much better way would be to use a function for this, like this...

function uppercaseWord(word) {
  return word[0].toUpperCase() + word.slice(1);
}

const uppercasePerson = uppercaseWord(person);
const uppercaseCity = uppercaseWord(city);

As you can see above, its much easier to use the function we created than having to write out the same logic.

Functions allow us to write logic once, and then call that function do what we need to.

By encapsulating this functionality inside a function, it allows us to write easier to use and more maintainable code.

Function declarations and expressions

function-declaration.png

When it comes to creating functions, there are a few ways we can create them. The first way is to use a function declaration (sometimes called a named function) and it looks like this...

function sayHello() {
  console.log('Hello!');
}

sayHello(); // We call a function by using its name and a pair of ()

However, this isn't the only way to create functions, but it is the most common.

Another way to create functions is to use the following syntax...

const sayHello = function () {
  console.log('Hello');
};

sayHello(); // We can call the function the same way

This is called a function expression, it works by assigning an anonymous function to a variable, so in this case we assign an anonymous function to the variable sayHello. We can use a function expression the same way as defining a named function.

One question you might have now is, what's the difference between using a function declaration and using a function expression?

Well, most of the time it will be very similar, but there are a few differences when it comes to hoisting and I would recommend reading this article to learn more about it.

Parameters

We can pass values into our functions by using what is called a parameter, so for example, if we wanted to create a function that adds two numbers, we could do this...

function add(num1, num2) {
  return num1 + num2;
}

// This allows us to do things like this

let value = add(2, 8); // -> 10
value = add(value, 10); // -> 20

Parameters allow us to create reusable functions. However, its important to keep in mind that the more parameters we add to our functions, the more complex and messy our code becomes.

We want to create functions with as few parameters as possible, so they are easy to use.

Default parameters

You can also define default parameters to make your functions a bit easier to work with...

function add(num1, num2 = 10) {
  return num1 + num2;
}

// So now we only need to pass in one parameter
let value = add(0); // -> 10
value = add(value); // -> 20

Arrow functions

In es6, we now have the ability to define what are called 'Arrow functions', these are similar to function expressions but look slightly different, for example...

const sayHello = () => console.log('Hello');

const addExclamation = (word) => {
  return word + ' !';
};

IIFEs

IIFEs or Immediately Invoked Function Expressions are functions that are immediately called on their declaration and they look something like this...

(() => console.log('hello'))(); // -> hello

To create an IIFE we usually wrap an anonymous function or arrow function with () and then we add another pair of () to call this function.

I would recommend checking out this article to learn more about using IIFEs

Functions are objects

Functions in JavaScript are a bit different than other programming languages. In JavaScript, functions are treated as first class citizens or first class objects. This means that functions can be treated just like JavaScript objects. We can reference functions with variables, we can pass functions as arguments to other functions, we can return them as values from other functions and we can even set properties on functions.

You might be wondering why would we want to use properties on functions? Well, one reason is for memoization.

Memoization allows a function to remember previously calculated values, this helps to increase performance on math heavy and complex computations.

A great, simple example of this in action is from the book Secrets of the JavaScript Ninja

function isPrime(value) {
  if (!isPrime.answers) {
    isPrime.answers = {};
  }

  if (isPrime.answers[value] !== undefined) {
    return isPrime.answers[value];
  }

  let prime = value !== 1; // 1 is not a prime
  for (let i = 2; i < value; i++) {
    if (value % i === 0) {
      prime = false;
      break;
    }
  }
  return (isPrime.answers[value] = prime);
}

In the above code example, we can see that we are setting a property on the isPrime function, this will be used to cache our computed values. So if we call this function with a value we have already calculated, it will just look inside our answers object and return that value, instead of doing the calculation again (looping to see if the value we entered is a prime number).

If you would like to learn more about memoization I recommend the following video

Generator functions

Generator functions allow us to create functions that can be exited and then re-entered at a later point within our program. The variables inside these functions are also stored, so that you are able to access them on each re-entrance.

The body of the generator function is not executed immediately, but instead an iterator object is returned that we can use to execute our generator function's body.

Generators are a bit confusing at first and I recommend reading the MDN documentation to understand them better.

Conclusion

Functions are awesome, they allow us to create clean and reusable code, as well as do useful things like memoization. In JavaScript, functions are one of the most important concepts to understand, so learning the basics of functions will go a long way.

Be sure to check out these resources to learn more