Download presentation
Presentation is loading. Please wait.
Published byMoses McKenzie Modified over 8 years ago
1
Programming with JavaScript Maureen Smith Professor, Saddleback College CIM 271B - Tutorial 8
2
Objectives w In this tutorial you will: Learn about the features of JavaScript Send output to a Web page Work with variables and data Work with expressions and operators Create a JavaScript function Work with arrays and conditional statements Learn about program loops
3
Session 8.1 w In this session you will learn about the development and features of JavaScript You’ll learn how to insert a JavaScript program into an HTML file and how to hide that program from older browsers that don’t support JavaScript Finally, you’ll write a simple JavaScript program to send customized output to a Web page
4
Introduction to JavaScript w So far you’ve created only static Web pages Content and layout don’t change w Now will create Web pages whose content and layout can be modified using built-in programs
5
Server-Side and Client-Side Programs w Have learn about accessing programs involving forms and CGI scripts Program was stored on and run off server Some disadvantages: Users have to be connected to the Web server to run CGI script Only the programmer of the script can alter the script itself System administrator can place limitations on how users access the script
6
Also poses problems for system administrator who has to be concerned about users continually accessing the server, slowing it down, and potentially overloading the system Prospect of even more users accessing server could mean costly machine upgrades to handle increased usage
7
w These issues led to development of programs, or scripts, that could be run from browser on user’s own computer (client) w Client-side programs solve many of the problems associated with CGI scripts Computing is distributed over the Web so no one server is overloaded with handling programming requests
8
Web pages containing client-side scripts can be tested locally without first uploading them to server Client-side program is likely to be more responsive to user (no wait for it to be sent over Internet) However, client-side programs can never completely replace CGI scripts
9
If you need to run a search form or process a purchase order, must be run from central computer because it will most likely contain the database
10
The Development of Java and JavaScript w Client-side programming came from unexpected sources In early 90s, before Web became hugely popular, programmers at Sun Microsystems saw a day when even common consumer devices (refrigerators, garage door openers) would all be networked and capable of being controlled by a single operating system
11
They began to develop such an operating system and based it on a language called Oak Oak was designed to be extremely reliable and flexible Project did not succeed, but Oak worked so well that Sun realized that it could be used on Internet Was modified in 1995 and renamed Java
12
w Sun also released a product called HotJava which could run programs written in Java HotJava acted as a Java interpreter, which means that it was able to interpret a Java program and run it for the user Idea was that Java programs would run inside Java interpreters, and because Java interpreters could be created for different operating systems, users could run Java in any environment
13
Including UNIX, Windows, DOS, Macintosh operating systems Just as Web pages are designed to be platform- independent, so was Java w Advantages of Java were immediately apparent Netscape incorporated a Java interpreter into Navigator 2.0 making HotJava unnecessary for Navigator users
14
IE followed suit, beginning with version 3.0 w With Java, user downloads a program, called an applet, along with the Web page Browser, with built-in Java interpreter, is able to run applet from user’s machine, freeing up server for other purposes w One problem was that nonprogrammers found it difficult to learn and use
15
Also needed access to JDK (Java Developer’s Kit) first to create the programs and compile them Compiling is process by which a program is converted from readable text file into an executable file To simplify process, a team of developers from Netscape and Sun created JavaScript--a subset of Java with several differences
16
Don’t need to work with developer’s kit or compile a JavaScript program JavaScript commands can be inserted directly into an HTML file rather than being placed in a separate applet Saves browser from having to download a separate file when page is accessed Not as powerful as Java, but simpler to use and meets needs of most people
17
Figure 8-3 highlights differences between Java and JavaScript w Several versions of JavaScript have been developed; most recent is 1.3 Figure 8-4 lists versions and describes how Netscape and IE support them IE actually uses a variation of JavaScript called JScript
18
For all practical purposes, JScript is identical to JavaScript, but some JavaScript commands are not supported in JScript, and vice versa Should always test JavaScript programs on several browsers w Like HTML and CSS, development of a JavaScript standard has been turned over to an international body called ECMA
19
European Computer Manufacturers Association Standard developed by them is called ECMAScript, though browsers will still use common name JavaScript Latest version is ECMA-262 which most major browsers support, though some areas have not been implemented w Other client-side programming languages are also available
20
Can use IE scripting language, VBScript w Because of the nearly universal support of JavaScript, will use this language in your work for North Pole Novelties
21
Running JavaScript w Task is to use JavaScript to create a page that calculates remaining days until Christmas for North Pole Novelties Andrew wants this info to appear on home page, shown in Figure 8-5, so that customers know how long they have to make their holiday purchase w Home page shows number of days remaining until Christmas
22
But this info has been explicitly entered into HTML file and works only if the date is June 27, 2001 Andrew wants this info to be calculated automatically for current date, whatever that might be And if the current date is between December 25 and December 31, wants page to display “Happy Holidays from North Pole Novelties”
23
w First task is to create and run a simple JavaScript program that sends output to Web page A JavaScript program is run by browser either when the page is first loaded, or in response to an event such as clicking a button or hovering over a hyperlink Will create a program that is run when browser loads home page
24
w There are two ways to create a JavaScript program Can place commands directly into HTML file Can also place commands in an external file Placing program in an external file allows you to hide the program code from user, whereas source code placed directly in HTML file can be viewed by anyone
25
However, an external file must be stored on server--added task of transferring both the Web page and JavaScript file to user Generally, the more complicated and larger the JavaScript program, the more likely you are to place it in an external file Will enter the code directly into the HTML file
26
w When you place JavaScript code directly into the HTML file, need some way of distinguishing it from text that you want to appear on page Otherwise browser might start displaying your JavaScript commands So this with the tag
27
Using the Tag w tag is a two-sided tag that identifies beginning and end of a client-side program Script commands and comments where URL is URL or filename of external document containing program code and language is language program is written in
28
SRC property is required only if you place program in separate file LANGUAGE property is needed so browser knows which interpreter to use Default LANGUAGE is JavaScript, and if you omit this property, browser will assume program is written in JavaScript
29
w Program can be placed anywhere within HTML file Either within tags or tags Many programmers favor placing their programs between tags in order to separate programming code from content Others favor placing programs in page’s body, at location where output is generated and displayed; we will do both
30
Hiding Your Script from Older Browsers w Older browsers that do not support JavaScript present a problem If they encounter JavaScript, will attempt to display them on page, treating script as part of content To avoid this, can hide script using comment tags w Have already used comment tags
31
JavaScript supports similar comment tags, using a set of double slashes (//) at beginning of a line to tell browser to ignore line and not interpret it as a JavaScript command w By combining HTML comment tag and JavaScript comment symbols, can hide program from browsers that don’t support tag
32
<!-- Hide this script from browsers that don’t support JavaScript JavaScript commands // Stop hiding from other browsers --> w When older browser encounters this code, first ignores tag
33
Next line it sees is start of HTML comment tag which doesn’t close until > symbol in second- to-last line So everything in JavaScript program is ignored Final tag is similarly ignored w Browser that supports JavaScript recognizes the tag and will ignore any HTML tags found between on and off tags
34
Passes the comment tag in second line and processes JavaScript program as written JavaScript comment (starting with //) is there to help other users understand and interpret code w Ready to insert code in order to hide the script from older browsers Delete HTML tags already in file that has date info because will eventually replace them with a program that works for any date
35
See NPN.html w With tags and comments in place, next task is to write a JavaScript program that sends output to page Because you haven’t yet learned how to either determine current date or calculate number of days until Christmas, this program will display a simple text string
36
Sending Output to a Web Page w JavaScript provides two methods to display text: The document.write() and document.writeln() method document.write(“text”); document.writeln(“text”); where text is a string of characters you want to appear on page
37
Following will display “Only 45 days until Christmas” document.write(“Only 45 days until Christmas”); w Both methods reflect the object-oriented nature of JavaSript Here “document” is an object (the page that browser is accessing) and “write” or “writeln” are actions that can be applied to the document
38
For now, when term “method” is used, understand that it means an action applied to something existing on page or in browser w Most of the time will use document.write() method Document.writeln() method differs from document.write() in that it attaches a carriage return to end of each text string sent to page
39
Becomes relevant only when text string is preformatted with tag for which browser recognizes existence of carriage returns w Text string created with document.write() method is enclosed within double or single quotation marks Allows you to include single/double quotation marks as part of text string
40
document.write(“Come meet David ‘Bud’ Davis”); will display text Come meet David ‘Bud’ Davis (including single quotation marks) Can display double quotation marks by enclosing text string within single quotation marks w Not limited to displaying only text
41
Can also include HTML tags in text string to format text and insert images document.write(“ News Flash! ”); displays text News Flash! formatted with header tag w Most JavaScript commands and names are case-sensitive Browser will not recognize “Document.Write()” and give error message
42
w Each JavaScript command line ends with a semicolon to distinguish it from next command line in program Sometimes semicolon is optional, but should still use it to make code easier to follow w Will now add document.write() method to JavaScript program just created in NPN.html file
43
w Will create a simple program to display the number of days until Christmas, assuming that the current date is December 15, 2001 See NPN_10.html w Have completed first JavaScript program! Does nothing more than display text you could have entered directly, but it’s a program you’ll build upon to perform more sophisticated tasks
44
Session 8.2 w In this session you will learn some of the fundamentals of JavaScript language Will learn how to create variables and how to work with different data types Will learn about expressions and operators and how to use them to change the variable values Finally, will create your own JavaScript function and use it in a program
45
Working with Variables and Data w Have inserted text using document.write() method Had to specify text explicitly; program did not more than as if you had placed the text directly Next task is to have your program determine current date and display it on the page w To do this, will create a JavaScript variable
46
A variable is a named element used to store and retrieve info Useful because they can store info created in one part of the program and use that info in another part Could create a variable named “Year” to store value of the current year and then use the Year variable at different locations in your program To assign value 2001 to variable “Year”: Year=2001;
47
w With Year variable assigned a value, can use document.write() method to display this value: document.write(Year); w This code would cause text “2001” to appear Can also combine text with the variable value by using a plus symbol (+)
48
document.write(“The year is “ + Year); This will display text The year is 2001 w In your program you won’t explicitly enter date info Instead, your program will determine current date and year for you and store that info in a variable so you can use date from variable later in the program
49
For now will learn about variables by entering a fixed value w Following restrictions apply to variable names: First character must be either a letter or an underscore (_) Rest of the characters can be letters, numbers, or underscores Variable names cannot contain spaces
50
Cannot use words that JavaScript has reserved for other purposes Cannot name a variable “document.write” w Variable names are case-sensitive If your JavaScript isn’t working properly, might be because you did not match case
51
Types of Variables w JavaScript supports four different types of variables: Numeric String Boolean Null w A numeric variable can be any number 13, 22.5, -3.14159
52
Numbers can be expressed in scientific notation: 5.1E2 for the value 5.1 X 10 2, or 510 A string variable is any group of characters such as “Hello” Strings must be enclosed in double or single quotation marks, but must be consistent ‘Hello’ is acceptable; “Hello’ is not Boolean variables are variables that can take only one of two values, either true or false
53
Use Boolean variables in situations in which you want the program to act in a particular way, depending on whether a condition, represented by the Boolean variable, is true or false A null variable is a variable that has no value at all Will happen when you have created a variable but have not assigned it a value yet Once a value has been given, it will fall into one of the other three data types
54
Declaring a Variable w Before you can use a variable, have to create it Also known as declaring a value Declare a variable in JavaScript using the var command or by assigning the variable a name Any of the following will create a variable named “Month”:
55
var Month; var Month=“December”; Month=“December”; w First command creates the variable without assigning it a value Second and third both create the variable and assign it a value w Considered good style to include var command whenever you create variables
56
Helps you keep track of variables program will use and makes it easier for others to interpret your code Many programmers place all their variable declarations at beginning along with comments describing each variable’s purpose w Now will create some variables Today, which will contain info about current date and time
57
ThisDay, which will store current day of the month ThisMonth, which will store a number indicating the current month ThisYear, which will store a number indicating the current year DaysLeft, which will store number of days until Christmas See NPN_14.html
58
w Now that you’ve declared the variables, need to use JavaScript methods to calculate variable values
59
Working with Dates w You will be working with dates as you try to calculate number of days remaining until December 25 JavaScript does not provide a date data type as some other programming languages do However, allows you to create a date object, which is an object that contains date info Date object can then be saved as a variable in your JavaScript program
60
There are two ways to save a date as a variable: variable=new Date(“month, day, year, hours:minutes:seconds”) or variable=new Date(year, month, day, hours, minutes, seconds) where variable is the name of the variable that will contain the date info and month, day, etc. indicate the date and time
61
Keyword new indicates that you’re creating a new object Note that in the first command form you specify the date using a text string and in the second you use values Each of the following will create a variable named “SomeDay” corresponding to a date of June 15, 2001 and a time of 2:35p:
62
SomeDay=new Date(“June, 15, 2001, 14:35:00”); or SomeDay=new Date(2001, 5, 15, 14, 35, 0); w In this example, might notice a couple of quirks in how JavaScript handles dates First, when you specify month with values rather than text, must subtract 1 from the month number
63
JavaScript numbers the months starting with 0 for January up through 11 for December So in second command, date for June 15 is expressed as (2001, 5, 15…) Also note that hours are expressed in military (24-hour) time (14:35 rather than 2:35) w If you omit hours, minutes, and seconds values, JavaScript assumes that the time is 0 for all
64
If you omit both date and time info, JavaScript returns current date and time, which it gets from system clock Following command creates a variable named “Today” that contains info about current date and time: Today=new Date(); This is exactly what you will eventually want
65
w Now that you’ve seen how to store date and time info in a variable, can add that feature Eventually will want to set Today variable to whatever current date is For now will use a specific date, October 15, 2001 See NPN_15.html
66
Retrieving the Day Value w The Today variable now has all the date and time info you need Unfortunately, it’s not in a form that will be very useful Problem is that JavaScript stores date and time info as a numeric value--number of milliseconds since January 1, 1970 All of JavaScript date and time functions are numerical calculations of these hidden numbers
67
Fortunately, you don’t have to do the calculations that translate those numbers into dates Can use built-in JavaScript date methods For each part of the date that you want visible (or used in a calculation) need a date method to retrieve its value w For example, second variable is ThisDay which will contain the day of the month
68
To get just that info, apply getDate() method to date variable DayValue=DateObject.getDate() where DayValue is name of a variable that will contain the day of the month and DateObject is date object or a date variable that contains the complete date and time info To retrieve day of the month from Today variable: ThisDay=Today.getDate();
69
Retrieving the Month Value w Similar method exists for extracting value of the current month Named getMonth() One important point about this method: because JavaScript starts counting the months with 0 for January, need to add 1 to the month number JavaScript produces Following extracts current month number, increases it by 1, and stores it in a variable named ThisMonth:
70
ThisMonth=Today.getMonth()+1; w If current date is June 28, value of the ThisMonth variable will be 6
71
Retrieving the Year Value w Final date method you’ll be using is getFullYear() method Extracts the year value from date variable Following shows how you would store the value of the current year in a variable named ThisYear: ThisYear=Today.getFullYear(); If date stored in Today variable is October 15, 2001, value of getFullYear will be 2001
72
w Why is method name GetFullYear() and not simply getYear()? There is a getYear() method Problem with this date method is that it returns only last two digits of year prior to 2000 Instead of 1999, a date of 99 would be returned w The getYear() method returns a value of 2000 for year 2000
73
So if you use it to calculate the number of years between 1998 and 2000, would come up with an answer of 1902 years Classic example of a Y2K bug that caused so much concern The getFullYear() date method was introduced in JavaScript 1.3 to correct this problem and is supported by Netscape 4.5 and IE 4.0 or above
74
So even though there is a getYear() date method, should not use it if your program will be calculating the difference in dates before and after year 2000 We will use GetFullYear() method w See Figure 8-10 for date methods w Ready to modify your program to work with Today variable
75
Will still use a specific date to test the program See NPN_18.html w To display this date info on your page, use the command: document.write(“Today is “+ThisMonth+”/ “+ThisDay+”/”+ThisYear+” ”); w Haven’t calculated value of DaysLeft variable yet
76
At this point, will set this value equal to 999 and learn how to calculate true value shortly See NPN_18a.html w Have completed second item on your task list by displaying date info Next step is to take those date values and use them to calculate days remaining until December 25 Will work with expressions, operators, functions
77
Working with Expressions and Operators w Expressions are JavaScript commands that assign values to your variables Have already worked with several expressions Used DaysLeft=999 to assign the value 999 to DaysLeft variable Expressions will always use some sort of assignment operator, such as = sign, but can also contain variety of other operators, which are elements that perform actions within the expression
78
A simple example is the + operator which performs action of adding or combining two elements Used the plus operator with following command: var ThisMonth=Today.getMonth()+1; w This command uses the + operator to increase value returned by GetMonth() method by 1
79
Also used + operator to combine text strings: document.write(“Only “ + DaysLeft + “days until Christmas”); w In both examples, plus operator combines two or more values or elements to create a single value or element
80
Arithmetic Operators w The + operator belongs to a group of operators called arithmetic operators Perform simple math calculations Figure 8-13 lists some of the arithmetic operators and gives examples of how they work w Some of the arithmetic operators are also known as binary operators because they work on two elements in an expression
81
There are also unary operators which work on only one variable These include the increment (++), decrement (--), and negation (-) operators The increment operator can be used to increase the value of a variable by 1 In the following, the value of the x variable is 100 and the value of the y variable is 101:
82
x=100; y=x++; w The decrement operator has the opposite effect, reducing the value of a variable by 1 Following assigns the value 100 to the x variable and 99 to the y variable: x=100; y=x--;
83
w Finally, the negation operator simply changes the sign of a variable: x=-100; y=-x; Here the value of the x variable is -100 and the value of the y variable is opposite that, or 100
84
Assignment Operators w Expressions assign values using assignment operators Have already seen one example, the equals (=) sign JavaScript provides other assignment operators that manipulate elements in an expression and assign values within a single operation One of these is the += operator
85
In JavaScript, the following create same result: x= x + y; x += y w In both the value of the x variable is added to the value of the y and stored in x w An assignment operator can also be used with numbers to increase a variable by a specific amount
86
To increase the value of the x variable by 2, can use either of the following: x= x + 2; x += 2 w Other assignment operators are shown in Figure 8-14 w Once you master the syntax, assignment operators are efficient and compact
87
As you start learning JavaScript, might prefer using longer form for such expressions
88
The Math Object and Math Methods w Another way of performing a calculation is to use one of the built-in Math methods These methods are applied to an object called the Math object Syntax for applying a math method: value = Math.method(variable); where method is the method you’ll apply to a variable and value is resulting value
89
To calculate absolute value of a variable named NumVar, use “abs” method: AbsValue=Math.abs(NumVar); and the value of the AbsValue variable is set to the absolute value of the NumVar variable Figure 8-15 lists other math methods As usual, case is important with JavaScript commands
90
Must type “Math” instead of “math” when using these commands
91
Creating JavaScript Functions w Can use all the JavaScript different expressions and operators to create your own customized functions A function is a series of commands that either performs an action or calculates a value Consists of the function name which identifies it; parameters, which are values used by the function; and a set of commands that are run when the function is used
92
Not all functions require parameters General syntax is: function function_name(parameters) { JavaScript commands } where function_name is the name of the function, parameters are the values sent to the function, and JavaScript commands are actual commands/expressions used by the function
93
Note that curly braces are used to mark the beginning and end of the commands in the function Group of commands set off by curly braces is called a command block and command blocks exist for other JavaScript structures in addition to functions w Function names, like variable names, are case-sensitive
94
Function name must begin with a letter or underscore and cannot contain any spaces w Are not limited in the number of function parameters a function contains Parameters must be placed within parentheses (following function name) and each parameter must be separated from others with a comma
95
Performing an Action with a Function w To see how a function works, consider the following which displays a message with the current date: function ShowDate(date) { document.write(“Today is “ + date + “ ”); } w Function name is ShowDate and it has one parameter, date
96
There is one line in the function’s command block, which displays current date along with a text string To run a function, you insert a JavaScript command containing the function name and any parameters it requires This process is known as calling a function To call the ShowDate function, could enter the following commands:
97
var Today = “3/25/2001”; ShowDate(Today); w Here the first command creates a variable named “Today” and assigns it the text string “3/25/2001” Second command runs ShowDate function, using value of the Today variable as a parameter
98
Result of calling the ShowDate function is that the following sentence appears: Today is 3/25/2001
99
Returning a Value from a Function w Can also use a function to calculate a value This process is also known as returning a value and is achieved by placing a return command along with a variable or value at the end of the function’s command block Consider the following Area function: function Area(Width, Length) { var Size = Width*Length; return Size; }
100
w Area function calculates area of a rectangular region, given its width and length, and places the value in a variable named “Size” Value of the Size variable is then returned by the function A simple JavaScript program that uses this function might appear as follows:
101
var x = 8; var y = 6; var z = Area(x,y); w First two commands assign values 8 and 6 to the x and y variables, respectively Values of both are then sent to Area function, corresponding to Width and Length parameters
102
Area function uses these values to calculate the area, which it then returns, assigning that value to the z variable Result is that 48 is assigned to the value of the z variable I hate math!
103
Placing a Function in an HTML File w Where you place a function is important Function definition must be placed before the command that calls the function If you try to call a function before it is defined, might receive error message from browser Although not a requirement, one programming convention is to place all function definitions used in the page between the tags
104
Ensures that each function definition has been read and interpreted before being called by JavaScript commands in body When browser loads HTML file containing a function, browser passes over the function and does not execute it Function will be executed only when called by another JavaScript command
105
Create the XmasDays Function w Now have all the info you need to create your own function, the XmasDays function Will have only one parameter, CurrentDay, which is the current date Function will return one value, the number of days between current date and December 25 of the current year Function will have three variables:
106
XYear: the current year XDay: the date of Christmas Initial value of this variable will be the date “December 25, 2001” DayCount: the number of days between current date and December 25 This is the value that will be returned by the function w Initial structure will look like:
107
function XmasDays(CurrentDay) { var XYear=CurrentDay.getFullYear(); varXDay=new Date(“December, 25, 2001”); var DayCount; return DayCount; } w First task is to set XDay to December 25 of current year
108
Might not be 2001! Do this using JavaScript setFullYear() method XDay.setFullYear(XYear); w If current year is actually 2002, date stored in XDay variable changes from “December 25, 2001” to “December 25, 2002” Next you calculate difference between December 25 and current date
109
DayCount=XDay - CurrentDay; w There’s a problem Remember that JavaScript stores date info in terms of milliseconds Taking difference between these two dates calculates the number of milliseconds before Christmas Hardly the info you want in the page!
110
so you have to convert this value by dividing the difference by the number of milliseconds in one day; this would then be: DayCount=(XDay - CurrentDay)/(1000*60*60*24); because there are 1000 milliseconds in a second, 60 seconds in a minute, 60 minutes in an hour, 24 hours in one day
111
w One more issue When user opens page, it’s unlikely that it will be exactly a certain number of days before Christmas More likely that it will be a certain number of days, plus a fraction of a day Andrew doesn’t want that fractional part displayed
112
Will remove the fractional part by rounding the value of DayCount to nearest day using round Math method DayCount = Math.round(DayCount); w Complete XmasDays function would then look as follows:
113
function XmasDays(CurrentDay) { var XYear=CurrentDay.getFullYear(); var XDay=new Date(“December, 25, 2001”); XDay.setFullYear(XYear); var DayCount=(XDay-CurrentDay)/1000*60* 60*24); DayCount=Math.round(DayCount); return DayCount; }
114
w Now that you see what the XmasDays function looks like will insert it into your file Following standard practice, will place code between tags Must place within a set of tags See NPN_25.html
115
w Next have to insert a command to call the function Recall that you previously set value of DaysLeft variable to 999 Will replace that command with one that calls XmasDay function using Today variable DaysLeft variable will then be set to whatever value is returned by XmasDays function
116
See NPN_26.html w Have completed XmasDays function Andrew will test page you’ve created and get back to you with any changes
117
Session 8.3 w In this session you will learn how to add decision-making capabilities to your JavaScript program through the use of conditional statements Will learn how to create and use arrays Will be introduced to program loops in order to run a command block repeatedly
118
Working with Conditional Statements w Only task remaining is to have the page display a greeting message in place of day count from December 25 through the 31st Need to create a conditional statement w A conditional statement is one that runs only under certain conditions Are many types; one most used is the If statement
119
if(condition){ JavaScript Commands} where condition if an expression that is either true or false If condition is true, JavaScript commands in command block are executed If condition is not true, no action is taken
120
Comparison and Logical Operators w To create a condition, need to use two types of operators: comparison and logical A comparison operator compares the value of one element with that of another, creating a Boolean expression that is either true or false Here are two examples: x < 100; y == 20;
121
w If x is less than 100, this expression returns the value true If x is 100 or greater, the expression is false In second example, y variable must have an exact value of 20 for expression to be true Uses a double equal sign rather than a single one Single equal sign is an assignment operator and is not used for making comparisons See Figure 8-19
122
w A logical operator connects two or more Boolean expressions One is the && operator which returns a value of true only if all the Boolean expressions are true Following will be true only if x is less than 100 and y is equal to 20: (x < 100) && (y == 20); See Figure 8-20
123
Using an If Statement w Now will see how these comparison and logical operators work in an If statement if(Day==“Friday”){ document.write(“The weekend is almost here!”);} w Here, if the Day variable is equal to “Friday,” text string is sent to page If Day is not equal to Friday, no action
124
Using an If…Else Statement w If statement runs a set of commands if condition is true, but does nothing if false Sometimes will want If statement to run one set of commands if condition is true and another if condition is false An If…Else statement does this if(condition){JavaScript Commands if true } else {JavaScript Commands if false}
125
where condition is an expression that is either true or false and one set of commands is run if true; another is run if false if(Day==“Friday”){ document.write(“The weekend is almost here!”); } else { document.write(“Hello!”);}
126
w If…Else structures can be nested, one within another if(Day==“Friday”){ document.write(“The weekend is almost here!”); } else { if(Day==“Monday”){ document.write(“Time for another work week”); } else {
127
document.write(“Hello”);} Here text “The weekend is almost here!” appears if day is Friday If day is Monday, text “Time for another work week” appears On other days text “Hello” is generated w Have similar situation on North Pole page
128
If current date is before December 25, page should display number of days until Christmas as calculated by XmasDays function Otherwise (if date is between December 25 and 31), should display a holiday greeting w Can distinguish between two situations by creating an If…Else statement that looks at the value returned by XmasDays function
129
If that value is positive, current date is before December 25 and page should display number of days left If value is 0 or negative, current date is December 25 or later and a holiday message should be generated Code is:
130
if(DaysLeft > 0){ document.write(“Only “ + DaysLeft + “ days until Christmas”); } else { document.write(“Happy Holidays from North Pole Novelties”);} w Replace previous document.write() method See NPN_31.html
131
See NPN_31a.html w Next will deal with some of the things Andrew wants you to change
132
Using Arrays w Some feedback indicates that the date format looks dry and uninviting Instead of “Today is 10/15/2001,” would rather see “Today is October 15.” w No built-in JavaScript methods to display dates in this format, so will create your own One way would be to create a series of conditional statements based on value of ThisMonth variable
133
And then display a different text string for each month Would require 12 nested If…Else statements! Can do it more simply by using arrays w An array is an ordered collection of values referenced by a single variable name var variable = new Array(size); where variable is name of array variable and size is number of elements (values) in array
134
Specifying a size is optional If you don’t specify a size, JavaScript will automatically increase the size of the array as you add more elements Code for creating an array named “Month” would be: var Month = new Array(); w Once array is created, create values for each individual element in the array
135
Month[1] = “January”; Month[2] = “February”; Month[3] = “March; etc. w These commands create 12 new elements in Month array Each element is identified by its index, which is an integer that appears between the brackets
136
Element “August” has an index value of 8 in Month array First element in any array has an index value of 0, second item has 1, etc. In Month array, there are actually thirteen total elements First element, Month[0] is not shown and has a null value because you want the index number to match the month number
137
Seems counterintuitive to assign December an index value of 11, though one could write a program that way if one chose w Can also use variables in place of index values If variable “IndexNumber” has value 5, then: Month[IndexNumber] would be equal to value of Month[5] which is “May”
138
w Can use arrays to create a function named “MonthTxt” Function has one parameter, “MonthNumber” which is the number of a month, and the function returns the name of that month function MonthTxt (MonthNumber) { var Month = new Array(); Month[1]=“January”;
139
Month[2]=“February”; Month[3]=“March”; etc. return Month[MonthNumber];} Command MonthTxt(10) will return text “October” This is what to add to HEAD section so that the name of the month rather than the number will show
140
See NPN_34.html w Next will use value of the ThisMonth variable to call this function and then store results in a new variable named “MonthName” Will then display name of month along with the day of the month See NPN_35.html
141
w Now need to remove test date and allow page to use current date If you don’t specify a date value, current date and time are automatically used See NPN_36.html
142
Working with Loops w Andrew may have future JavaScript programs he wants you to run Programming often involves creating code that does not run just once (as this page), but is repeated an indefinite number of times w To provide this capability, must use a program loop A program loop is a set of instructions that is executed repeatedly
143
Two types: loops that repeat a set number of times before quitting, and loops that repeat until a certain condition is met Create the first type using a For statement
144
The For Loop w The For loop allows you to create a group of commands that will be executed a set number of times through use of a counter, which tracks the number of times the command block has been run Set an initial value for the counter, and each time the command block is executed, the counter changes in value
145
When counter reaches a value above or below a certain stopping value, the loop ends for(start; condition; update) { JavaScript Commands } where start is starting value of counter, condition is a Boolean expression that must be true for loop to continue, and update specifies how the counter changes in value each time the command block is executed
146
Like a function, the command block in the For loop is set off by curly braces This loop displays several lines of text: for(Num=1; Num<4; Num++) { document.write(“The value of Num is “ + Num + “ ”); } w The counter is the variable Num, which starts with an initial value of 1
147
As long as the value of Num is less than 4, the condition for running the loop is met When value of Num reaches 4, loop stops Finally, expression “Num++” indicates that each time the command block is run, value of Num increases by 1 (example of increment operator) When this For loop is run, following lines will be generated:
148
The value of Num is 1 The value of Num is 2 The value of Num is 3 and then the loop will end
149
The While Loop w Similar to For loop is the While loop Also runs a command group as long as a specific condition is met But does not employ any counters while(condition) { JavaScript Commands } where condition is a Boolean expression that can be either true or false
150
As long as the condition is true, the group of statements will be executed var Num=1; while(Num<4) { document.write(“The value of Num is “ + Num); Num++; } w Produces same result as For loop But used in different situations
151
Would use a While loop instead of a For loop in situations in which there is no counter variable and you want more flexibility in halting the program loop w Have completed your study of JavaScript
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.