DEV Community

Cover image for Functions in JavaScript
anetasargsyan
anetasargsyan

Posted on

Functions in JavaScript

Another essential part of programming is function. So…

What is a function?

The function is a set of statements that are executed when the function is called.

Let’s first understand how a function is constructed and what it means to call a function.

To create a function, we will use a new keyword - function. This will tell that what comes after it is a function. Then we need to name our function. The same rules work here for naming a function, except that you can have multiple functions with the same name. Just the thing is, the program will consider the last one only. After the name, we have parenthesis, in which we write arguments for our function(there may be none). Then we open curly brackets, which identify the body of the function. When the function is called, whatever is in its body gets executed. Now let’s get into details.

function ExampleWithNoArguments(){
    //do something
}

//calling the function with no arguments
ExampleFunctionWithNoArguments(); 

function ExampleWithMultipleArguments(a, b, c){
    //add a, b and c, and return the value
    var sum = a + b + c;
    if(sum > 0){ 
        return(sum); 
    } else {
        return(-sum);
    }
}

var Sum = ExampleWithMultipleArguments;
//type of Sum will be a function, since we assigned a function to it
//aka you can call "Sum" just the way you call 
ExampleWithMultipleArguments

var sumOfNums = ExampleWithMultipleArguments(-5, -6, -8); 
//type of sumOfNums will be number since function RETURNS number

function ExampleFunction(argument){
    var message = "My argument: " + argument;
    console.log(message);
    return message;
}
ExampleFunction("some random string");

Enter fullscreen mode Exit fullscreen mode

Let’s consider the last one.

The function is the keyword, “ExampleFunction” is the name of our function, what is inside brackets is the argument, and in curly brackets is the body, which will be executed when called.

In the following line, the function is called with a string argument with a value of “some random string.” To call a function, we simply write its name, open brackets, and write inside of its arguments if we have any. And that’s it. The body of the function will be executed.

As one of my beloved teachers once explained: function is like a factory, you give it raw materials, and it works on them and then returns a result to you.

In our case argument is the raw material. When we call this function, a variable with the name of “argument” is created, and it takes the value which we give in parenthesis (in our case, “some random string”). The important thing is this variable is local to the function it belongs to, which means you cannot use this parameter outside of the function’s body. So, ExampleFunction takes the argument and prints in the console “My argument: “ + “some random string” (as our argument has this value).

Functions may have many parameters and may have none as shown in the example. It is not recommended to have many parameters for a single function to avoid messing things up. Also, they may and may not return a value.

Returning value from a function

In JavaScript, functions are variables, which means you can create a variable and assign a function to it. If you do this without calling the function, the variable will take the reference to that function.

function ExampleWithMultipleArguments(a, b, c){
    //add a, b and c, and return the value
    var sum = a + b + c;
    if(sum > 0){ 
        return(sum); 
    } else {
        return(-sum);
    }
}

var Sum = ExampleWithMultipleArguments;
//type of Sum will be a function, since we assigned a function to it
//aka you can call "Sum" just the way you call 
ExampleWithMultipleArguments

var sumOfNums = ExampleWithMultipleArguments(-5, -6, -8); 
//type of sumOfNums will be number since function RETURNS number
//output: 19

Enter fullscreen mode Exit fullscreen mode

And if you return something, your variable will take that as a value.

I keep repeating, “return a value.” Returning a value means giving the result of some actions, as shown in the factory example. You gave arguments (raw material) to the function (the factory) and got a value returned (result). After returning function stops its execution, which means you cannot have more than one return statement in a function, as only the first one will give away the result and stop the execution of the function. However, you may say, how come we have two return statements in the example? The answer is inside the if statement, so if we had a negative number, the program would ignore the first brackets and jump to the second one. In the end, only one of those statements will be executed.

!Note.

The function's return value is the value of the called function.

Function inside of a function

Since the function is just a variable that does some operations to get its value, it can be declared inside a function. You can have multiple functions created inside of a function.


//takes two arguments, gives their product's absolute value 
//as a result
function ProductOfAbsolutes(x, y){

    //is a function, with argument x, which has the value 
   //of x's absolute
    var absoluteOfNumber = function(a){

        //returns (value) absolute of x
        return Math.abs(a);
    }

    //is a function, with 2 arguments a and b, returns 
//their product
    var product = function(a, b){

        //gives the value of a times b
        return a * b;
    }

    //this is return statement for "ProductOfAbsolutes" function
    //first it calls the function "absolteOfNumber" 
    //with argument x, then with y

    //then puts their outputs as arguments to function "product"
    //returns the product
    return product(absoluteOfNumber(x), absoluteOfNumber(y));
}

console.log(ProductOfAbsolutes(2.5, -5)); // output: 12.5
Enter fullscreen mode Exit fullscreen mode

Here’s an example of that. Just remember, what’s declared inside the body, stays in the body(most of the time). (Body is { inside of these }).

Additional

Just to give an idea of why we need functions, we can always write things when they need to be executed. This helps A LOT with repetitions. If you need to multiply two numbers, then find the square root of the result, then take the negative of that number and divide by 5 for some reason, and you need to do this more than once, you may find it exhausting to write that over and over again, making it complicated not only for you but for the computer as well. Here come the functions. If you need a neater code, or you have some part that will be repeated multiple times (like playing some sound when a user clicks a button), the functions come in handy. They make your project more understandable, easier to navigate, and in the end, have a beautiful structure.

Thank you for bearing with me this far! If you have any questions, leave a comment, I will answer as soon as I see.))

Top comments (1)

Collapse
 
goyafan_33 profile image
Edita Haroyan

butiful