const - JS | lectureJavaScript Fundamentals 2

Functions

JavaScript Fundamentals 2

Functions are the fundamental building blocks of real-world JavaScript applications. They are one of the most essential concepts in the language.

We can define a function as a piece of code that we can repeatedly reuse in our code. It's a little bit like a variable but for whole chunks of code. A variable holds a value, but a function can contain one or more complete lines of code.

To declare a function, we start with the function keyword and define a function name. Let's now create a simple function that will log something to the console.

script.js
function introduce() {
  /* The function body */
  // Code executed when we run this function
  console.log('My name is Jacob and I am a Software Engineer');
}

As you can see and as I said previously, a function is composed of the function keyword ( function), a function name (introduce), parenthesis, which I'm going to explain later why we need it and the curly braces to create the so-called function body.

Now that we have created our function, we can use it as many times as we want. To use the function, we write the function name followed by parenthesis:

script.js
introduce();

Using this function by doing introduce() is called invoking the function, running the function, or calling the function. We can now use or run this function as many times as we want, and each time we call the function, the code inside that function will get executed.

If you now try to run the below code:

script.js
introduce();
introduce();
introduce();
introduce();

You will notice that we get 'My name is Jacob and I am a Software Engineer' four times because we called the function four times, and so the function body was executed four times.

We will now use some more functionalities of functions because they can do a lot more than simply reusing a line of code as we did previously.

Usually, when writing functions, we also pass data into a function. Additionally, a function can also return data, which means giving us data back that we can then use for something else in our code.

Let's have an example of a simple function that adds two numbers:

script.js
function addMyNumbers(firstNumber, secondNumber) {  console.log(firstNumber, secondNumber);  const answer = `The result of the addition of ${firstNumber} and ${secondNumber} is ${
    firstNumber + secondNumber
  }`;
}
return answer;

You can see from the above code that I highlighted three lines. Remember when I told you that I was going to explain the use of parenthesis? Well, the time has come! Parenthesis allows us to pass what we call parameters to our function body.

Parameters are like variables specific only to the function that gets defined once we call the function. In our case, on the first highlighted line, we have two parameters, firstNumber and secondNumber, specific to our function addMyNumbers and defined when we call our function addMyNumbers.

On the second highlighted line, which is the first line of code in the function body, you can see that we are logging the function parameters just as if they were normal variables inside the function. After logging, we are building a string using the input data that we get into the function.

Now comes the cool part, which is the third highlighted line where we use the return keyword. The return keyword helps us to return any value from the function. In our case, we are returning the result of the operation, which we can then use anywhere later in our code.

Now let's call, run or invoke our function addMyNumbers.

script.js
addMyNumbers(2, 3);

On calling our functionaddMyNumbers, we can see that we specify the actual values for the parameters firstNumber (2) and secondNumber (3). Consider the parameters firstNumber and secondNumber as empty spaces we need to fill out when writing our function. When we then call the function addMyNumbers(2,3), we fill the blank spaces by passing the real specific values that will get assigned to the parameters. The actual values (2 and 3) of the function parameters are referred to as the function's arguments.

After executing our script, we have 2 3 printed in our console, which are exactly the values we specified when calling our function. You are now certainly asking yourself, what about the answer variable? Where is it? Well, the answer variable was returned from this function. Meaning the result of running our function is the answer variable that we just returned. Basically, this means that once the function addMyNumbers(2,3) is executed, it is replaced by the result of the function and in this case the answer string we created.

If we now want to use the returned value of our function, we need to store it in a variable like this:

script.js
const additionResult = addMyNumbers(2, 3);
console.log(additionResult); // Result ==> The result of the addition of 2 and 3 is 5

To recap what happens, we call the function addMyNumbers with two arguments, 2 and 3, and these arguments are the actual values of the function's parameters, firstNumber and secondNumber. When the function is executed, firstNumber will be 2 and secondNumber will be 3; we then use these values to build the answer string that gets returned from the function. This means basically that the result of calling addMyNumbers(2,3) will be the answer variable that was just returned, which is then saved by storing it in our variable additionResult which we later logged to the console.

However, we can directly log the function to the console without necessarily capturing and storing the returned value into a variable and get the same result.

script.js
console.log(addMyNumbers(2, 3)); // Result ==> The result of the addition of 2 and 3 is 5

So thanks to the power of functions, we can reuse our function addMyNumbers with different input values and get different outputs. For example:

script.js
const anotherAddition = addMyNumbers(10, 5);
console.log(anotherAddition); // Result ==> The result of the addition of 10 and 5 is 15

It may be obvious, but note that when we create a function we should call it at least once because if we never call our function addMyNumbers then the code inside that function will never be executed making our function kind of useless.

Back to our introduce function, you can see that it has no parameters, so when calling the function we specified no argument even though we could. If we tried to do something like this:

script.js
introduce('Ulrich');

The argument will not get used because when creating the function we didn't provide any parameters. So providing an argument or not when calling the function will not have any effect.

You can also notice that the introduce function doesn't return anything, and that's not a problem because not all functions need to return something, and not all functions need to accept parameters like our addMyNumbers function.

So keep in mind that the introduce function does not return anything. All it does is just logging a message to the console, which has nothing to do with returning a value. It does not produce a value because we don't return anything from the function reason why we didn't saved it into a variable. Technically it does produce undefined but that isn't really relevant.

That's basically the fundamentals of functions. It was probably confusing if this was your first contact with functions. Try to read over again if that wasn't clear enough because it's really important to understand these concepts.

To finish this lecture, we can say that functions allow us to write more maintainable code because with functions, we can create reusable chunks of code instead of manually writing the same code repeatedly. It is a very important principle for writing clean code that is used in programming all the time. This principle is known as the DRY principle, which means Don't Repeat Yourself.