Java Practical Class

JAVA SCRIPT

 Variables

   A variable is simply a name given to a value. Variables can be given different values throughout the course of a JavaScript program.

You can declare a variable using the var command:

var example;

In this line, you have defined a variable named example, which currently has no value. It is also possible to assign value to a variable when you declare it:

var example = “An Example”;

comments:

   JavaScript supports two types of comments:

   A single-line comment begins with two slashes (//) and ends at the end of the line.

   A multiple-line comment begins with the /* delimiter and ends with the */ delimiter. This type of comment can include any number of lines. These work like the comments in the C language.

Important function:

The parseInt Function

   The parseInt() function looks for an integer number as the first part of the string. It ignores the decimal portion, if found. For example,

   this statement assigns the variable a to the value 39:

   a = parseInt(“39 steps”);

   number from the text string variable:

   a = parseInt(text,16);

   The parseFloat Function :

   The parseFloat() function is similar to parseInt(), but works with floating-point values. It attempts to find a decimal floating-point

   The eval Function :

   The eval() function has many uses in sophisticated programming techniques, and you’ll see it many times throughout this book. Rather

   than looking for a number in a string, eval() looks for any valid JavaScript expression. A simple example assigns 25 to the a variable:

   a = eval(“20 + 1 + 4”);

   Integers

   An integer is simply a number that does not include a decimal. Integers in JavaScript can be only positive numbers. You can use an integer as a literal in JavaScript simply by including the number. For example, this statement prints the number 47:

   document.write(47);

   JavaScript considers any number without a leading zero to be a decimal (base 10) number. You can also use data in hexadecimal (base 16) and octal (base 8). Here is a summary of the syntax you use to specify different types of numbers with examples:

   Decimal: no leading zero (57, 5000)

   Hexadecimal: prefix with 0x (0x56, 0xFE)

   Octal: leading 0 (045, 013)

   Floating-Point Numbers

   You can also use floating-point decimal numbers in your JavaScript programs. These can be used to represent just about any number

   conveniently. A simple floating-point value consists of an integer followed by a decimal point and a fractional value, such as 2.01.

   Unlike integers, floating-point values can be either positive or negative. You can specify negative values for floating-point numbers by adding the negative sign to the beginning of the number, as in -3.1. Any number without a negative sign is assumed to be positive.

   You can also use a form of scientific notation to refer to floating-point numbers. This makes it easy to specify very large numbers. To use this notation, you include the letter E (either upper- or lowercase) followed by the exponent, either positive or negative.

   a few examples of exponent notation and the decimal numbers they represent:

   1E6: One million (1,000,000)

   1.5E9: 1.5 billion (1,500,000,000)

   25E-2: One-quarter (.25)

   1E-6: One-millionth (.000001)

   4.56E5: 456,000

   Boolean Values

   Boolean values are the simplest data type. They can contain one of two values: true or false. Because they can represent an on/off or

   1/0 state, these are sometimes called binary values.

   Strings

   Another important type of value you can work with in a JavaScript program is a string. Strings are simply groups of characters, such as

   “Hello” or “I am a jelly doughnut.”.

   You can include strings as literals in JavaScript by enclosing them in double or single quotation marks. Here are some examples of values

   that JavaScript will treat as strings:

   “This is a string.”

   ‘A’

   ’25 pounds’

   “200”

   Special Characters

   Along with alphanumeric characters, you can use a variety of special characters in JavaScript strings. These include carriage returns, tabs, and other nonprintable characters.

   To use one of these special characters, include a backslash (\) followed by the code for that character. The codes are as follows:

   \a: Alert (bell) character (produces a bell sound)

   \b: Backspace character (moves the cursor back one character)

   \f: Form-feed character (indicates a new page on a printer)

   \n: New line character (indicates a new line of text)

   \r: Carriage return character (moves the cursor to the beginning of the line)

   \t: Tab character (advances the cursor to the next tab stop)

   Functions

   A function accepts parameters and returns a value. Functions offer the ability for programmers to group together program code that performs a specific task—or function— into a single unit that can be used repeatedly throughout a program. You can also define your own functions with the function keyword. This example defines a very simple function that adds two

   numbers:

   function Add(a,b){

      var result = a + b;

      return result;

   }

To use a function, you simply include the function’s name, followed by the parameters in parentheses. For example, here is a simple script

   that uses the Add() function to print a result:

   var test = Add(2,4);

   document.write(“Two plus four equals:”,test);

   Creating an Array

   Many languages support arrays-numbered sets of variables. For example, scores for 20 different students might be stored in a scores array. You could then refer to scores[1] for the first student’s score, scores[5] for the fifth student, and so on. This makes it easy to

   define a large number of variables without having to give each one a name. The number in the brackets is called an index into the array.

   JavaScript does not support arrays as variables. Instead, they are handled as objects. You can create an array by using the Array object. As an example, this statement creates an array called scores with 20 values:

   scores = new Array(20);

   Once you define the array, you can access its elements by using brackets to indicate the index. For example, you can assign values for the

   first and tenth scores with these statements:

   scores[0] = 50;

   scores[9] = 85;

      The if…else Construct

   The if statement is the main conditional statement in JavaScript.

      if (a == 1) {

      document.write(“Found a 1!”);

      a = 0;

   }

   else {

      document.write(“Incorrect value: ” + a);

      a = 0;

   }

   Using the for Keyword

   One of the main reasons for computer programs is to perform repetitive tasks.

   for (i=1; i<10; i++) {

      document.write(“This is line “,i,”\n”);

   }

   Using while Loops

   The other keyword for loops in JavaScript is while. Unlike for loops, while loops don’t necessarily use a variable to count. Instead,

   they execute as long as (while) a condition is true. In fact, if the condition starts out as false, the statements might not execute at all.

   while (total < 10) {

   n++;

   total += values[n];

   }

   The break Statement :

   There is one way out of an infinite loop. The break statement can be used during a loop to exit the loop immediately and continue with the

   first statement after the loop:

   while (true) {

   n++;

   if (values[n] == 1) break;

   }

   The continue Statement :

   One more statement is available to help you control the execution of statements in a loop. The continue statement skips the rest of the

   loop, but unlike break, it continues with the next iteration of the loop:

   for (i=1; i<21; i++) {

   if (score[i]==0) continue;

   document.write(“Student number “,i, ” Score: “, score[i], “\n”);

   }

   Types of Events

Event NameDescription
onAbortOccurs when the user aborts the loading of an image
onBlurOccurs when an object on the page loses focus
onChangeOccurs when a text field is changed by the user
onClickOccurs when the user clicks on an item
onErrorOccurs when a document or image can’t load correctly
onFocusOccurs when an item gains focus
onLoadOccurs when the page (or an image) finishes loading
onMouseOverOccurs when the mouse pointer moves over an item
onMouseOutOccurs when the mouse pointer moves off an item
onSelectOccurs when the user selects text in a text area
OnSubmitOccurs when a submit button is pressed
OnUnloadOccurs when the user leaves the document or exits

   Using String Objects

      Any string of characters in JavaScript is a string object. The following statement assigns a variable to a string value:

   text = “This is a test.”

   Because strings are objects, you can also create a new string with the new keyword:

   text = new String(“This is a test.”);

   string objects have a single property, length, which reflects the current length of the string. There are a variety of methods

   available to work with strings:

   indexOf() finds an occurrence of a string within the string.

   substring() returns a portion of the string.

   toString() can be used on non-string values and converts them to strings.

   toUpperCase() converts all characters in the string to uppercase.

   toLowerCase() converts all characters in the string to lowercase.

   There are also a few methods that enable you to change a string’s appearance when it appears in an HTML document:

   big() displays big text, using the <BIG> tag in HTML 3.0.

   bold() displays bold tag, using the <B> tag.

   fixed() displays fixed-font text, using the <TT> tag.

   fontcolor() displays the string in a colored font, equivalent to the <FONTCOLOR> tag in Netscape.

   fontsize() changes the font size, using the <FONTSIZE> tag in Netscape.

   italics() displays the string in italics, using the <I> tag.

   small() displays the string in small letters using the <SMALL> tag in HTML 3.0.

   strike() displays the string in a strikethrough font, using the <STRIKE> tag.

   sub() displays subscript text, equivalent to the <SUB> tag in HTML 3.0.

   sup() displays superscript text, equivalent to the <SUP> tag in HTML 3.0.

   As an example, this statement prints the value of the text string in italics:

   document.write(text.italics());

   Using Date Objects

   The Date object is a built-in JavaScript object that enables you to conveniently work with dates and times. You can create a Date object any time you need to store a date, and use the Date object’s methods to work with the date.

   birthday = new Date();

   birthday = new Date(“June 20, 1996 08:00:00”);

   birthday = new Date(6, 20, 96);

   The Date object will not work with dates before January 1st, 1970.

   setDate() sets the day of the month.

   setMonth() sets the month. JavaScript numbers the months from 0 to 11, starting with January (0).

   setYear() sets the year.

   setTime() sets the time (and the date) by specifying the number of milliseconds since January 1st, 1970.

   setHours(), setMinutes(), and setSeconds() set the time.

   getDate() gets the day of the month.

   getMonth() gets the month.

   getYear() gets the year.

   getTime() gets the time (and the date) as the number of milliseconds since January 1st, 1970.

   getHours(), getMinutes(), and getSeconds() get the time.

   The Math Object

   Rounding and Truncating

   Three of the most useful methods of the Math object enable you to round decimal values up and down:

   Math.PI is the ratio of a circle’s circumference to its diameter (approximately 3.14159).

   The methods of the Math object enable you to perform mathematical functions. The methods are listed in the following sections in

   categories.

   Algebraic Functions

   Math.cos() calculates the cosine of a number.

   Math.sin() returns the sine of a number.

   Math.tan() calculates the tangent of a number.

   Statistical and Logarithmic Functions

   Math.exp() returns e (the base of natural logarithms) raised to a power.

   Math.log() returns the natural logarithm of a number.

   Math.max() accepts two numbers and returns whichever is greater.

   Math.min() accepts two numbers and returns the smaller of the two.

   For example, this statement assigns the big variable to the larger of x and y:

   big = Math.max(x,y);

   Basic Math and Rounding

   Math.abs() calculates the absolute value of a number.

   Math.ceil() rounds a number up to the nearest integer.

   Math.floor() rounds a number down to the nearest integer.

   Math.pow() calculates one number to the power of another.

   Math.round() rounds a number to the nearest integer.

   Math.sqrt() calculates the square root of a number.

   As an example, the following statement assigns the x variable to the square root

   of 25:

   x = Math.sqrt(25);

   Random Numbers

   Math.random() returns a random number between 0 and 1.

   The window Object

   The window object is at the top of the object hierarchy. A window object exists for each open browser window. The properties of this object describe the document in the window and provide information about the window.

   Windows Object’s properties

One of the simplest window object properties enables you to manipulate the status line-the gray-background line at the bottom of the window.

window.status=”Text”;

   The window.open() method enables you to open a new browser window. A typical statement to open a new window looks like this:

   WindowName=window.open(“URL”, “WindowName”, “Feature List”);

The window.close() method closes a window.

temp =window.confirm(‘Would you like to confirm?’);

   alert() displays an alert dialog.

   blur() removes focus from the window, sending it to the background.

   close() closes a window you have opened.

   confirm() displays a confirmation dialog and returns true or false.

   prompt() prompts the user and returns the text entered.

   Document:

   The document object represents the current document in the window and is a child of the window object. It includes the following

   properties:

   bgColor is the background color, specified with the BGCOLOR attribute.

   fgColor is the foreground (text) color, specified with the TEXT attribute.

   write() writes text to the document window.

THE END

Leave a Comment

Your email address will not be published. Required fields are marked *

Shopping Cart