Functions in JavaScript

JavaScript , Fri Dec 30 2022

    Functions Intro

    In this section, we're going to talk about functions. I'm really excited to show you how functions work!

    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. Remember that, a block of code designed to perform a particular task. We will often need to perform a similar task many times in our application.

    Functions are the main building blocks of the program. They allow the code to be called many times without repetition.

    You've already seen a function in JavaScript. Not only that you've seen it, you've used it multiple times by now.

    It was the function called console.log. Console.log has a task of printing values to the console. After finishing this section, 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:

    A function is a special value with one purpose: it represents some code in your program.

    Functions are handy if you don't want to write the same code many times. "Calling" a function like tells the computer to run the code inside it and then go back to where it was in the program. There are many ways to define a function in JavaScript, with slight differences in what they do.

    Defining functions

    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;
    }

    A lot of stuff is written, let's review it word by word.

    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 when calling it. The function square takes one parameter, called number.

    Names of parameters do not matter, you can name them however you'd like.

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

    Everything else up to the closing curly brace represents the function body. In function body we can write all of the things we learned so far about JavaScript.

    We can create variables, do something with operators, add if/else statements and so on.

    This example function is consisted of one statement that says to return the parameter of the function (that is, number) multiplied by itself.

    The return is really important, every function needs to have it. It specifies the value that will be returned by the function.

    And how can we retrieve values from functions? We need to call them.

    Let me explain what do I mean by that.

    Calling Functions

    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:

    square(5);

    In 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 5, the parameter called number in the function declaration is going to become number 5. Then, we multiply it by itself and return it.

    25

    As you can see, we get 25 when we run it.

    That's the return value of the called function with an argument of 5. So how can we actually use the value from the function?

    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% percent 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 return it instantly, in one line:

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

    Arrow Functions: 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 are more limited than regular functions — for example, they have no concept of this whatsoever.

    When you write this inside of an arrow function, it uses this of the closest “regular” functions above.

    This is similar to what would happen if you used an argument or a variable that only exists in the function above.

    Practically, this means that people use arrow functions when they want to “see” the same this inside of them as in the code surrounding them.

    Parameters vs Arguments

    If you're 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. 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 name, with firstName.

    const sayHi = (firstName) => {
        console.log(`Hi, ${firstName}`);
    }

    sayHi('Joe');

    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 'Joe'. 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 24 years old.