Functions in JavaScript

Functions in JavaScript

Functions are one of the most interesting & most important parts of any programming language. So what are functions, and why should we use them? A JavaScript function is a block of code designed to perform a particular task. We will often need to perform a similar task many times in our application and functions help in doing that easily. Functions are the main building blocks of the program. They allow the code to be called many times without repetition. Functions are handy if you don’t want to write the same code many times. Calling, a function tells the computer to run the code inside it and then go back to where it was in the program.

You've already seen a function in JavaScript. Not only that you've seen it, but you've also used it multiple times by now. It was the function called console.log. Console.log has the task of printing values to the console. After finishing this blog, you'll be able to create your own functions as well! When talking about functions, you're often going to hear two terms: function declaration and function call. So let's explain each one of these.

Function Declaration

A function declaration consists of the function keyword. I'm first going to show you an example of a simple function called square:

function square(number){
    return number * number;
}
  • function is the reserved JavaScript keyword for creating a function.

  • square is the name of the function, you can name it, however, you'd like.

  • Then inside of parentheses, we have something known as parameters. Parameters are values we're going to send to our function while calling it. The function square takes one parameter, called number (the names of parameters do not matter, you can name them, however, you'd like).

Then, we have an opening curly brace. It represents the start of the function block.

And how can we retrieve values from functions? We need to call them. Let me explain what I mean by that.

Function Calling

Defining a function does not execute it. Defining it simply names the function and specifies what to do when the function is called. Calling the function actually performs the specified actions with the indicated parameters. For example, if you define the function square, you could call it as follows:

let value = square(10);
console.log(value)          // 100

Here, we have the function name followed by parentheses, in parentheses, we put something known as arguments. Arguments are the values we want to fill our parameters with. For example, if we send the value of 10, the parameter called number in the function declaration is going to become 10. Then, we multiply it by itself and return it.

After the function returns the square of the given argument we can store it in a variable (in this case value is the variable). Now you can use the value in whatever way you want.

Arrow Functions

They have only one difference from "normal" functions. Arrow functions do not create their own this value. "this" is a special JS reserved keyword, we're going to explain it later in detail. The only thing you should know right now is that arrow functions do not create their own "this" value. In 99% of the cases, we're not even going to need it. The most modern way of declaring functions is using something known as arrow functions. It looks like this:

const square = (number) => {
    return number * number;
}

Arrow functions also have a shorter and more concise version. Whenever we only have one return statement inside of the function and nothing else, we ran to return it instantly, in one line:

const square = (number) => number * number;

Arrow functions are similar to function expressions. It’s one of the features introduced in the ES6 version of JavaScript They’re concise and are often used for one-liners.

Arrow functions have a number of benefits compared to traditional function syntax.

  • Concise syntax: Arrow functions have a shorter syntax than traditional functions, which can make your code more readable and easier to understand.

  • Implicit return: If your function only has one expression, you can omit the curly braces and the return keyword, and the expression will be returned automatically.

  • Lexical binding: Arrow functions use lexical scoping, which means that this keyword is bound to the value of this in the surrounding scope. This can make your code more predictable and easier to reason about.

Parameters vs Arguments

If you are new to JavaScript, you may have heard the terms parameters and arguments used interchangeably. While very similar, there is an important distinction to make between these two keywords.

  • Parameters are used when defining a function, they are the names created in the function definition. The parameter is like a variable that is only meaningful inside of this function. It won't be accessible outside of the function.

  • Arguments are real values passed to the function when making a function call.

If we go back to our example, we would say that our function accepts one parameter. Parameters can be named anything. The only thing that matters is the order. Let's try replacing the name, with firstName.

const greeting = (firstName) => {
    console.log(`Hi, ${firstName}`);
}
greeting('John');         //Hi, John

Nothing changed, our function still works. That means that parameters are just names we create for the arguments we're planning to pass into the function. As you can see, when calling the function, we have one argument. The argument is a real JavaScript value, in this case, a string of 'John' and the parameter is 'firstName'.

Let's try adding another parameter to practice a bit more. Let's say that we want to take in both the name and the age of the person. To do that, we'd need to add a second parameter, separated by a coma. Now, we also need to provide an argument to fill the value of age. We can do that when making a function call:

const logAge = (name, age) => {
    console.log(`${name} is ${age} years old.`);
}
logAge('John', 25);     //John is 25 years old