JavaScript

Tuesday April 8, 2025
updated: April 10, 2002

 
Home
Getting Started
Lesson 1
Lesson 2
Lesson 3
Lesson 4
Lesson 5
Lesson 6
Lesson 7
Lesson 8
Resources
Credits

 

 


Lesson 7: FUNCTIONS

There are two parts of a function: The definition and the call.

Defining the function simply names the function and specifies what to do when the function is called. Functions should be defined in the <head></head> of the HTML document.

Calling the function actually performs the specified actions which are usually defined in the <Head>. In this lesson the function is called when the button is clicked on.

Functions are only stored, and are not executed until certain actions are performed by the user of the web page. Defining a function in the Head guarantees that functions are loaded before the user has a chance to do anything that might call a function. This is important because if an undefined function is called, this will lead to an error. It is also a good idea to define functions in the <head> because it makes your code modular so you can use the same function as an event handler for many different items. This also makes your code easier to read.

Variables and Functions

When you declare a variable within a function, the variable can only be accessed within that function. When you exit the function, the variable is destroyed. These variables are called local variables. You can have local variables with the same name in different functions, because each is recognized only by the function in which it is declared.

If you declare a variable outside a function, all the functions on your page can access it. The lifetime of these variables starts when they are declared, and ends when the page is closed.


© 2002 Tracy Johnson