Javascript- Functions () Tutorial 


               


Javascript- Functions () Tutorial


Javascript


Functions are code that performs a certain task when called.

A programmer can program a function to do anything, such as create an alert pop-up box that displays text to a user, creates a prompt box that asks a user for a question, anything imaginable, a function can be programmed to.

In this article, we will go over how to create javascript functions and how to call them so that the functions do the actions they are programmed to do.


How to Name a Function in Javascript

Before we go over how to create a function in javascript, let's go over how functions are named in Javascript.

Functions always follow the format:

functionname() {

}

The function has any name that you want it to have and then it's followed by an opening and closing parentheses. Popupalert(), Username(), and Userphonenumber() are all valid javascript functions.

The function has to have parentheses because some functions must have parameters passed to them in order to do their action. However, we'll start with simple functions which don't need parameters passed to them.


How to Create a Function

Now that you know how to name a function, we'll go over how to create one.

The format to create a function is:

functionname() {
//Lines of Code of what function is to do
}

So if we want a function to display a pop-up alert box that says, "Welcome to this site", the lines of code would be:

Popupalert() {
alert("Welcome to this site");
}

If we want a function that creates a pop-up prompt box that asks a user for his or her age, the lines of code would be:

Userage() {
var age= prompt("Please Enter Your Age", "");
}

The reason we place the prompt function to the age variable is because we need to store the value of what the user enters so that we can later do an if-else statement based on the user's age. But this is the function which would create a prompt box for the user's age.


How to Call a Javascript Function

Above, we've created functions, but we haven't called them, so they're not going to be executed for a user until they're called in the code.

How do we call javascript functions?

We call javascript functions by the following format:

functionname();

All you have to do is enter the function name and add a semicolon after it. This is statement. All statements in javascript must end with a semicolon.

So to call all the other functions above, the code would be:

Popupalert();
Userage();

And this is how you call functions in javascript so that they will execute and perform the action which you program it to do.


HTML Comment Box is loading comments...