Functions in JavaScript

Functions in JavaScript

ยท

6 min read

Functions are an integral of every modern programming language as they provide programmers with the ability to write reusable code and get the ball rolling in their projects. JavaScript functions like many other parts of JavaScript have features that are not talked about as much as they should. What I want this article to achieve is to give you a better understanding of JavaScript functions by talking about its cool features. We will begin by talking about the basics (what functions are) to gain a sense of direction and then move on to the different ways you can create a function. We will finish off with interesting concepts like closures and recursion.

Function

A function in its simplest form is an encapsulated block of code designed to perform a particular task. We use functions every day. Every time you pick up your phone or calculator to do simple arithmetic you are making use of a bunch of functions.

Most programmers think of functions as some "special" kind of data structure. It turns out functions are just objects that store up a collection of values like other JS objects. I don't want to drift from the main idea of this article by going into detail about functions being objects. You can watch this YouTube video to learn more.

JavaScript has different syntaxes for creating functions. In all of them, the common denominator is using the function keyword, the exception being when you use the arrow function syntax (more on this later) to create a function. Using the function keyword, you can create a function by simply passing it as a value to a variable (binding) as shown in the code below:

let helloWorld = function() {
    console.log("Hello World!")
}

When a function is created as seen above, it is called a function expression. Within the parentheses () is where you provide the function with inputs. When you are creating the function, these inputs are called parameters and when the function is being invoked(called) to perform the task it was created for, these inputs are called arguments. However, some developers parameters and arguments interchangeably.

A more widespread syntax for creating a function is using the function declaration syntax. When you use this syntax, you don't have to create a variable as the name of the function is also the name of the variable that holds it in memory. Here is an example of a function declaration.

function hello(name) {
    console.log("Hello " + name)
}

hello("John Rambo")

// Output: Hello John Rambo

Aside the tiny difference in syntax for function expressions and declarations, the only other difference between them is that when you create a function using the function declaration syntax, you can invoke the function even before you create it. This sounds weird but is made possible by a feature called hoisting that allows function and variable declarations (only for variables declared with var ) to be placed at the top of their scope when your code is being interpreted by the JavaScript interpreter.

For functions that are created using the function expression syntax, you can only use them after they have been created because function expressions are not hoisted so trying to do so will result in a ReferenceError.

With the arrow function syntax you don't use the function keyword. The arrow function syntax is similar to the function expression syntax but without the function keyword. Here is a code example of the arrow function syntax.

let helloWord = (name) => {
   console.log("Hello " + name)
}

As you can see the arrow function syntax is less verbose than the others and you can further break it down by omitting the parentheses when the function has only one parameter and omitting the braces when the code the inside the braces is a single line. By doing that the function above becomes.

let helloWorld = name => console.log("Hello " + name)

The only difference that exists between the arrow function syntax and the other two syntaxes is the value of their this keyword. This is beyond the scope of this article so I won't go into the thick of it. If you are curious and want to learn more about it, check this out. Now, unto the main events: recursion and closures.

Recursion

Recursion is the act of a function calling itself, it is used to solve problems that contain smaller sub-problems. A recursive function can receive two inputs: a base case (ends recursion) or a recursive case (resumes recursion).

MDN Web Doc

When you using recursion you have to create a mechanism that will break the recursion at some point or you will end up with an infinite loop. Below is a simple example of a recursive function.

function recursiveCountDown(num) {
  if (num <= 0) {
    console.log("The Count Down has ended!");
    return;
  }
  console.log(num);
  recursiveCountDown(num - 1);
}

The function above is a regular countdown function that calls itself recursively reducing 1 from the previous number that was passed as the argument to the function each time it runs. The moment the number being passed to the recursive function becomes 0 we end the recursion loop by printing a message to the console and then exiting the function with the return keyword.

Closures

Closures refer to the combination of a function and its surrounding state that is its lexical scope. I agree with you if you think those are just a bunch of words that don't really tell you what closures actually are. So let's break it down.

What all this means is that inner functions are able to the access variables declared within the outer functions within which they exist but these variables are not accessible to any function that is outside this outer function. This brings us to the final definition that a closure is function that is able to reference (access) variables from the local scope surrounding it. Here is a code example from the MDN Docs to help you understand what we are talking about:

function init() {
  var name = "Mozilla"; // name is a local variable created by init
  function displayName() {
    // displayName() is the inner function, that forms the closure
    console.log(name); // use variable declared in the parent function
  }
  displayName();
}
init();

In the code example we have declared a function called init that has a variable name . Within this init function, we have created a function called displayName that is able to reference the name variable declared in its parent function init . That right there is all you really need to understand about closures.

Conclusion

After having explored all these about JavaScript functions, it is time for you to go on to use them in your JavaScript projects to make sure you don't forget what you have learned. Thank you for sticking with me to the end.