Broad Network


Function Basics in ECMAScript 2015

ECMAScript Basics - Part 9

ECMAScript 6

Foreword: In this tutorial I explain the basics of ECMAScript functions.

By: Chrysanthus Date Published: 12 May 2016

Introduction

This is part 9 of my series, ECMAScript Basics. A Function is a set of statements that perform a specific task. When you will get to writing programs, you will realize that programs are very long. You will realize that there are groups of statements that will have to be carrying out the same task in different parts of the code (program). You do not need to type this group of statements in different parts of the code. You can type it once, and then call it wherever it is needed in the code. In this tutorial I explain the basics of ECMAScript functions.

Defining Functions
The group of statements form the function, but you need to group them in a particular way. By doing this, we say you are defining a function in ECMAScript. In some computer languages, this process is split into two. One phase is called, declaring the function and another phase is called, defining the function. For this article and for basic ECMAScript programming, we shall use a single process, which is defining the function.

A function definition consists of the following in the order given

- The reserved word, function.
- The identfier of the function.
- A list of parameters to the function, enclosed in parentheses and separated by commas (see below).
- The statements that define the function, enclosed in curly braces. The statements in a function can have among them calls to other functions defined in the current program (application).

Note: another name for reserved-word is keyword.

Example
In the following example, we define a function that will add two numbers, find the square of the sum and then return the result.

<script type="text/ECMAScript">

    function myFn ()
        {
            num1 = 2;
            num2 = 3;

            sum = num1 + num2;
            square = sum * sum;

            return square;
        }

</script>

The function begins with the reserved word, function. The identfier of the function is myFn. This is followed by parentheses. Then you have the block. In the block, you have the declaration and assignment of the two numbers. The third statement in the block sums the two numbers. The fourth statement squares the sum. The last statement returns the square to the statement that would call the function, outside the function. The reserved word, return, is used for this. It is followed by a variable or a literal. Not all functions end with the return instruction. Some functions just perform a task and do not return anything.

Calling a Function
You call a function by just typing the identifier of the function, followed by parentheses, in a statement. The following code illustrates this. Try it:

<!DOCTYPE HTML>
<html>
<head>
</head>
<body>

<script type="text/ECMAScript">

    function myFn()
        {
            num1 = 2;
            num2 = 3;

            sum = num1 + num2;
            square = sum * sum;

            return square;
        }

    result = myFn();
    alert(result);
</script>

</body>
</html>

The extra HTML code is to produce a web page.
This code is similar to the previous with the addition of two last statements. The last-but-one statement calls the function. This statement is outside the function. The right operand of the statement is “myFn()”. It is this expression that calls the function. When it calls the function, it receives the value returned by the return statement in the function. This value is now assigned to the variable, result. The last statement displays the result.

A function call does not always have to assign a return value to a variable. Functions that do not have return values are called by just typing the identfier, followed by parentheses (then semicolon, to form a statement).

Parameters and Arguments
Now in the above function we can only deal with two particular numbers, which are 2 and 3. This is a disadvantage. If we declare and assign the variables (identifiers) outside the function, then we can always change the values of the variables, then send the variables to the function before the function is executed. In this way, we shall be able to deal with many other pairs of numbers. The following example illustrates this:

<script type="text/ECMAScript">

    num1 = 4;
    num2 = 5;

    function myFn(no1,no2)
        {
            sum = no1 + no2;
            square = sum * sum;

            return square;
        }

    result = myFn(num1,num2);
    alert(result);

</script>

This time the variables have been declared and assigned outside the function. Some other function elsewhere in the code can actually change these values. However, a function cannot change the value of a variable inside some other function. In the definition of the function, the parentheses now have two variables. These variables in this position are called Parameters. These parameters of the function are used within the function.

In the last-but-one statement, where the function is called; the parentheses have two variables. These variables in this position are called Arguments. These arguments of the function are the variables declared outside the function. The arguments to a function call, can be literals, something like:

    result = myFn(4, 5);

Read the above code and try it.

It is advisable to always make the variables for the parameters different from the corresponding variables for the arguments. If you do not do this, then while manipulating the parameters within the function, you might change the values of the variables outside the function.

Default Argument Value
Imagine that in the above example, one number is fixed, and the other can be changing. For example, assume that num2 will always be 5 and num1 can be any other number such as 2, 4, 6, 15, etc. In this case, the only identifier declared (created) would be num1. To achieve this, the fixed number will be made, one of the function parameters as the following example shows:

    <script type="text/ECMAScript">

        num1 = 2;

        function myFn(no1, no2=5)
            {
                sum = no1 + no2;
                square = sum * sum;

                return square;
            }

        result = myFn(num1);
        alert(result);

    </script>

When something is kept fixed like this, we say it is the Default Argument Value. You just have a parameter identfier and assign a value to it in the parentheses of the definition of the function. Note that in the function call, only one identifier (num1) has been used. You do not need to include the default argument value in the function call. The result alerted (displayed) is 49.

Optional Argument
For the default argument position at the function call, when you do not type any value, the default (fixed) value is used inside the function called. However, if you give a value other than the default value at the default position in the function call, that value is used in the function called instead of the default (fixed) value. Read and try the following code:

    <script type="text/ECMAScript">

        num1 = 2;

        function myFn(no1, no2=5)
            {
                sum = no1 + no2;
                square = sum * sum;

                return square;
            }

        result = myFn(num1, 6);
        alert(result);

    </script>

The result alerted is 64. This means, the default parameter is also an optional parameter, in the sense that an argument may be present (typed) or absent, in the default position, during the function call.

We have come to the end of this part of the series. Rendezvous in the next part.

Chrys

Related Links

ECMAScript Basics
ECMAScript Operators
Expressions in ECMAScript
Statements in ECMAScript
Custom Objects in ECMAScript
Functions in ECMAScript
ECMAScript Date Object
The ECMAScript String Object
ECMAScript String Regular Expressions
ECMAScript Template Literal
The ECMAScript Array
ECMAScript Sets and Maps
ECMAScript Number
Scopes in ECMAScript
Mastering the ECMAScript (JavaScript) eval Function
Sending Email with ECMAScript
ECMAScript Insecurities and Prevention
Advanced Course
Advanced ECMAScript Regular Expressions
Promise in ECMAScript 2015
Generator in ECMAScript 2015
ECMAScript Module
More Related Links
Node Mailsend
EMySQL API
Node.js Web Development Course
Major in Website Design
Low Level Programming - Writing ECMAScript Module
ECMAScript Course

BACK NEXT

Comments

Become the Writer's Follower
Send the Writer a Message