Broad Network


ECMAScript Function Basics

ECMAScript Basics - Part 9

Forward: In this part of the series, we learn how to define functions in ECMAScript.

By: Chrysanthus Date Published: 25 Jul 2012

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 doing 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 article I explain the basics of ECMAScript functions.

Note: If you cannot see the code or if you think anything is missing (broken link, image absent), just contact me at forchatrans@yahoo.com. That is, contact me for the slightest problem you have about what you are reading.

Defining Functions
The group of statements forms 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 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 name 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 name 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 name of the function, followed by parentheses, in a statement. The following code illustrates this. Try it:

<script type="text/ECMAScript">

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

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

            return square;
        }

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

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 name, 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 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.

Predefined Functions
Predefined functions are functions that are already defined by the ECMAScript Interpreter. They are called top-level predefined functions because they can be used anywhere in your code. We shall look at two of them. We shall also look at another special function that behaves like a top-level function.

parseInt
The parseInt function is used to convert an integer in the form of a string to a correct integer. "25" for example, is a string, whose content is an integer. After the conversion, you have the returned value that you can use in arithmetic operations. "25" as it is, is a string and cannot be used in arithmetic operations. Read and try the following code:

<script type="text/ECMAScript">

    num1 = parseInt("25");
    answer = num1 + 5;
    alert(answer);

</script>

parseInt is an ECMAScript top-level function. parseInt will also convert a float number to an integer. Read and try the following code:

<script type="text/ECMAScript">

    num1 = parseInt(57.863);

    alert(num1);

</script>

parseInt truncates off the decimal part; it does not round the number.

parseFloat
This is the second top-level function we shall look at. It converts a float number, which is in the form of a string to a proper float number. After the conversion, you have the returned value that you can use in arithmetic operations. "32.45" as it is, is a string and cannot be used in arithmetic operations. Read and try the following code:

<script type="text/ECMAScript">

    num1 = parseFloat("32.45");

    answer = num1 - 6;

    alert(answer);

</script>

alert
We have seen this function before. It is actually an example of what is called a DOM window object method. Do not worry about that vocabulary for now. Just know that you can use this function as a top-level ECMAScript function. The argument to the alert function is a sting or a variable that holds the string. Read and try the following code (click the OK button of the first alert box to allow the second one to display):

<script type="text/ECMAScript">

    alert("I am a string.");

    var str = ("You also are a string.");

    alert(str);

</script>

The alert argument can also be an expression (see later).

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

Chrys

Related Links

Major in Website Design
Web Development Course
HTML Course
CSS Course
ECMAScript Course
NEXT

Comments

Become the Writer's Fan
Send the Writer a Message