JavaScript Basics

advertisement

JavaScript Basics

Modified from: WikiBooks, Microsoft http://en.wikibooks.org/wiki/JavaScript http://msdn.microsoft.com/en-us/library/ie/cte3c772%28v=vs.94%29.aspx

Introduction

JavaScript is a web programming language that is used to turn static web pages into dynamic and interactive web pages. An example use of JavaScript is a clock displayed on a web page that automatically updates itself to show the current time. JavaScript's design was influenced by many programming languages, including C, but is meant to be more usable by non-programmers.

JavaScript is not based on or related to Java; this is a common misunderstanding.

JavaScript is a Client-side programming language. JavaScript code (also called scripts) is included inside an HTML file or linked to from an HTML file. JavaScript code runs in the web browser of the user's machine after being downloading from a web server.

Some example uses of JavaScript are:

• rotating or scrolling text.

• making portions of a form visible or invisible. For example in an order form, if the user ticks a checkbox "deliver to different address", an extra section with text boxes with delivery street, name, number, and place may be made visible.

• drop down menus.

• validate user input on a form.

• computations without the need to go back to the server.

• determine type of browser current user is using.

• obscure some information from certain types of users, such as email addresses from bots.

JavaScript runs in the web browser, by a special utility called a JavaScript interpreter . Some older web browsers and text-only browsers don't have a JavaScript interpreter, or don't run

JavaScript's latest versions. Furthermore, some users turn off JavaScript in their browser by choice. Generally, web pages should use JavaScript to enhance the user's experience, rather than depend on it. This is often referred to as graceful degradation (i.e if the user has turned off

JavaScript, the page should always still load, presenting the same information but without the extra functionality provided by JavaScript.)

JavaScript Basics pg 1 of 10

The SCRIPT Tag

The

script

element

All JavaScript, when placed in an HTML document, needs to either be within a script element, or be called from an event handler . We will look at event handlers a little later. A script element can either contain JavaScript statements directly (referred to as an inline script ) , or the script element can link to an external JavaScript file. The script element may appear almost anywhere within the HTML file. A standard location is within the head element. Placement within the body however is allowed.

Inline JavaScript

A script element that contains inline JavaScript looks like:

<head>

<title>Home Page</title>

<script type="text/javascript">

// JavaScript code here

</script>

</head>

Inline scripting has the advantage that both your HTML and your JavaScript are in one file, which is convenient for quick development and testing. This is also used in situations where the

JavaScript code is specific to that one page.

The type attribute of the script element tells the browser which scripting language and which version of the scripting language is being used. Another client-side scripting language used in the

Internet Explorer (IE) browser is VBScript. The scripting language can be specified individually in the script element itself, and you may also use a meta tag in the head of the document to specify a default scripting language for the entire page.

<meta http-equiv="Content-Script-Type" content="text/javascript" /> or

<script type="text/javascript">

// JavaScript code here

</script>

Linking to external scripts

A script element that links to an external JavaScript file looks like:

<script type="text/javascript" src="script.js"></script>

JavaScript Basics pg 2 of 10

In the script element on the previous page, the src attribute of the script element identifies the URL of external JavaScript file you wish to link to. When the browser encounters the script element, it will open and read the contents of the external JavaScript file.

Having your JavaScript in a separate file is recommended for JavaScript functions which can potentially be used (shared) in multiple html pages. This way multiple html pages can link to the same JavaScript file and utilize the same JavaScript code. This makes it easier for updates to occur, because only one JavaScript file has to be updated and changed. This also saves space on the server, because each html page does not have to include redundant JavaScript code. Finally, placing JavaScript in a separate file also separates content (html) from behavior (JavaScript).

You can link to more than one JavaScript file from a single html page. In the example below, multiple script elements in a web page link to two different JavaScript files.

<script type="text/javascript" src="form_handling.js"></script>

<script type="text/javascript" src="functions.js"></script>

JavaScript Statements

Every JavaScript program is a collection o f one or more statements , where each statement carries out one complete task. Typically, a statement is written on a single line, although a statement can be written over two or more lines. Also, two or more statements can be written on the same line by separating them with semicolons (;). The semicolon (;) is used to explicitly terminate a statement, and is the JavaScript statement termination character .

The following is an example of two JavaScript statements, each terminated by a semicolon (;) and each on its' own single line. var length = 100; var width = 200;

The following is an example of two JavaScript statements, each still terminated by a semicolon

(;), but this time they are on the same line. var length = 100; var width = 200;

Hello World Program

As our first program, we will create a web page with inline JavaScript code that creates a pop- up box. We will nest the <script> element inside of the <head> element within the web page. The script will simply contain one JavaScript statement to display a pop-up box. Assuming the page is viewed in a browser that has JavaScript enabled, the browser will execute the statement as the page is loading.

Figure 1 is the web page with our first JavaScript program.

JavaScript Basics pg 3 of 10

<html>

<head>

<title>Page One</title>

<script type="text/javascript">

window.alert("Hello World!");

</script>

<meta charset="utf-8" />

</head>

<body>

<h1>Page One</h1>

<p>The content of page one.</p>

</body>

</html>

Figure 1. Page One

Let's now create a second web page that links to an external JavaScript file instead of containing an inline script. This external JavaScript file will simply contain one JavaScript statement to display a confirmation pop-up box. Figures 2 and 3 contain the web page and external

JavaScript, respectively.

<html>

<head>

<title>Page Two</title>

<script type="text/javascript" src = "pageTwo.js" >

</script>

<meta charset="utf-8" />

</head>

<body>

<h1>Page Two</h1>

<p>The content of page two.</p>

</body>

</html>

Figure 2. Page Two window.confirm("Would you like to continue?");

Figure 3. External JavaScript File

JavaScript Basics pg 4 of 10

JavaScript Language

Whitespace

Whitespace is the blank portions of JavaScript programs, which includes spaces, extra indents and line breaks. When the JavaScript interpreter executes a JavaScript program, the interpreter ignores instances of whitespace. Programmers, however, use whitespace to make the code easier to read.

The following is some JavaScript code with very little whitespace. var f_name="Joe"; var l_name="Smith"; alert("Hello "+fname+" "+lname);

The following is the same JavaScript code with a typical amount of whitespace. var fname = "Joe"; var lname = "Smith"; alert("Hello " + fname + " " + lname);

The following is the same JavaScript with a lot of whitespace. var fname = "Joe" ; var lname = "Smith" ; alert ( "Hello " + fname + " " + lname ) ;

All three code snippets above work exactly the same. The extra whitespace is ignored by the interpreter.

Comments

Comments allow you to leave notes in your code to help other people understand it. Many times you will develop web pages that other people will later have to enhance and maintain. Comments provide documentation that allows other people to understand what the code is do ing. Comments also allow you to disable code that you don't want to the interpreter to execute, but you don't want to delete. Commented code and documentation are ignored by the JavaScript interpreter.

There are single-line comments and multi-line comments.

Single-line comme nts

A double slash, // , turns all of the following text on the same line into a comment that will not be processed by the JavaScript interpreter.

// Shows a welcome message alert("Hello, World!")

JavaScript Basics pg 5 of 10

Multi-line comments

Multi- line comments are begun with slash asterisk, /* , and end with the reverse asterisk slash,

*/ .

Here is an example of how to use the different types of commenting techniques.

/* This is a multi-line comment that contains multiple lines of commented text. */ var count = 1; alert('count: ' + count); // this is a single-line comment

Case Sensitivity

The JavaScript programming language is case sensitive . Case sensitivity means that variable and object identifiers must be typed in the correct case, or programs will not execute correctly. For instance, when working with JavaScript objects, object names are always lowercase. This means that document.write() is valid, but Document.write() is invalid and will return an error.

Variables and Data Types

In mathematics, a variable is a value that may change within the scope of a given problem or set of operations. In computer programs, a variable is a named, temporary storage location that stores data for future use. Variables are named, because they are assigned a name that references the storage location. Variables are temporary, because they exist only during the program's execution. You will use variables to store, retrieve and manipulate values throughout your code.

Variable declaration

Declaring a variable means allocating a tiny portion of memory to store the value the variable will be assigned. Variables are explicitly declared by the var statement. Imagine we need out program to store a person’s email address. Below we use the var statement to define a variable named email that could store this informaiton. var email;

The above variable is created, but has the default value of undefined .

When declaring a variable, many times we want to assign the variable an initial value. Assigning an initial value to a variable is called initializing a variable. Below we use the var statement to declare and initialize a variable named email . var email = "webmaster@myblog.com";

JavaScript Basics pg 6 of 10

After being declared, a variable may be assigned a new value which will replace the old one: email = "joe@myblog.com";

Naming variables

When choosing variable names there are some rules that must be obeyed:

• Upper case and lower case letters of the alphabet, underscores, and dollar signs can be used

Numbers are allowed after the first character

• No other characters are allowed

Variable names are case sensitive: different case implies a different variable name

A variable may not be a reserved word

• The variable name should have meaning, and hint to the contents of what is being stored

Primitive Data Types

Variables can store different categories of information, referred to as data types . Some data types can only store a single value, called primitive data types, while some data types can store multiple values, called complex data types.

JavaScript supports the following primitive data types:

• Numeric

String

Boolean

Numeric Type

The Numeric data type is used to represent integers (positive and negative whole numbers) and real (positive and negative floating point) numbers. Numbers can be written with, or without decimals. Below we assign the variables x and y to numeric values: var x = 5.00; // Written with decimals var y = 5; // Written without decimals

We can also use the numeric data type to store extremely large or extremely small numbers through representing the numbers in scientific (exponential) notation. Below, we use the lowercase "e" is used to represent "ten to the power of": var y = 123e5; // 12300000 var z = 123e-5; // 0.00123

JavaScript currently supports numbers as large as 1.79769x10308, and as small as 5x10-324.

JavaScript Basics pg 7 of 10

String Type

A string data type is used to store a chain of zero or more characters (letters, digits, and punctuation marks). You use the string data type to represent textual information. The following are examples of strings:

"Happy am I; from care I'm free!"

'"Avast, ye lubbers!" roared the technician.'

"45"

'Happy Holidays to all my friends and family. I wish you all the best in the new year'

When representing strings, we always enclose a string between single quotation marks or double quotation marks. The quotation marks are used to delimit – identify the start and end of - the string. The important key to remember, is that if you use a single-quote to identify the start of a string, you must use a single-quote to identify the end. Similarly, if you use a double-quote to identify the start of a string, you must use a double-quote to identify the end.

The string data type is also used to represent a single character. To represent a single character in

JavaScript, you create a string that consists of only one character.

"c"

You can also represent an empty (zero- length) string in JavaScript. This is shown below as two quotes directly after one-another with nothing in-between.

""

Below is an example of how to declare a variable and assign to the variable a string value: var name = "John Doe";

If we are using a pair of double quotes to specify the start and end of a string, we have to take extra steps if we want to include a double quote as part of the string. For instance, imagine we want to store in a variable named dialog a string value as such: var dialog = "Bob said, "thanks, but no thanks"";

When the JavaScript interpreter reads the statement, it will read the start and end of the string value to be stored as highlighted below: var dialog = "Bob said, " thanks, but no thanks"";

In assigning the string value, we need a way to inform the interpreter that we do not want the double quote to terminate (close) the string. Rather we want that double quote to be part of the string.

JavaScript Basics pg 8 of 10

The solution is to place a backslash before the double quote, which informs the JavaScript interpreter to that the quote is not ending the string, but rather it is part of the string. We do so as follows: var dialog = " Bob said, \"thanks, but no thanks\" ";

Below is a similar example of how this would work with a string enclosed within single quotes: foo = ' It\'s cold today.

';

Placing a backslash before the quote is called escaping the quote. This informs the JavaScript interpreter not to treat the quote as the end of the string.

Boolean Type

Boolean variables can only have 2 possible values, true or false . Whereas the string and number data types can have a virtually unlimited number of different values, the Boolean data type can only have two. A boolean value is a truth-value, and is often times used in repetition and selection control structures to specifies whether the condition is true or not.

Below are examples of assigning boolean values to variables: var mayday = false; var birthday = true;

JavaScript Basics pg 9 of 10

Exercises

1.

Type the web page from Figure 1 in an HTML editor and save the file as pageOne.html

.

Open the pageOne.html

in a web browser to verify the JavaScript code works.

2.

Type the web page from Figure 2 in an HTML editor and save the file as pageTwo.html

.

Type the JavaScript statement from Figure 3 in an editor and save the file as pageTwo.js

. (Make sure to save the files in the same folder. Open the pageTwo.html

in a web browser to verify the

JavaScript code works.

3. Ans wer the following questions: a. What are the two ways JavaScript can be placed within an HTML page? b. What is the purpose of comments? c. What does it mean to declare a variable? d. What does it mean to initialize a variable? e. What are the two possible values for the boolean data type? f. Is 00age a valid variable name? Why or why not? g. Is top90dref a valid variable name? Is it a good variable name?

4. Write down the JavaScript statement to pe rform each tasks described below: a. declare a variable name and assign your name as the string value b. declare a variable date and assign the current date as the string value c. declare a variable color and assign the string green d. declare a variable count and assign the numeric value 0 e. declare a variable size and assign the numeric value 0.025 f. declare a variable found and assign the boolean value false g. declare a variable feedback and assign the value Bob's son said "I don't want to go to bed"

(hint: remember to escape the quotes as needed)

JavaScript Basics pg 10 of 10

Download