Content Menu

Home-What is JavaScript?

JavaScript tutorials

1. JavaScript Basics

2. JS Simple Coding

3. JS InterActive Content

4. Images and JS

5. JS Functions

6. JavaScript Events

7. JS Conditional

8. JS Loops

9. Other

Syntax- Defining Function in Javascript

There are certain elements that need to be defined for a function to work.

Syntax

function nameoffunction (var1, var2 ...........)
{
Code to be executed
}

Lets look at each of those parts

Example- JS Function

Functions are used in a variety of places in the website, most commonly with JS events. We will study events in detail in later lessons. First, lets look at a simpler example.

Step 1- Declare the function

We declared a function and named it 'contact'. This contains our lenghty contact info, we wish to display it multiple times on our page. NOTE- the example is to explain the concept to you in simple terms.(Real world application- you wish to display the info at end of every page- function kept in external JS file

declaring a Javascript function

Step 2- Call the Function

Call the function by its name where it is required.

calling javascript function

Result

function result

 

Example 2- Defining Function and using with Events

This is the most common use of functions. The function is called to execute its code, when a certain event occurs. Like when you click the buttons in the example below, it will display a JS Confirm message.

Step 1- Declare the function

declare function

Step 2- Call the Function

Call the function by its name where it is required.

 

js calling function

Note- in the example above, we have used the function thrice while the code is written in the head section of the page only once. This saves repitition and enforces consistency.