Chapter 21 Exercises 21-1 and 21-2
Introduction to JavaScript
Introduction to JavaScript
Home > Chapter Review and Exercises > Chapter 21 Exercises
Follow the instructions on pages 593-605 (Exercise 21-1) and pages 606-617 (Exercise 21-2) of the Class Text.
I have already created a folder in your Chapter 21 folder with the title.html file you will need to edit.
As reference, the Chapter 21 textbook slides are in the Class Textbook and Resources section.
NOTE: There are several website links here labeled PRACTICE. I encourage you to go to each of these to get a better understanding of the parts of JavaScript.
1. JavaScript is a programming language that your browser runs on your device.
2. Other programming languages are either compiled (meaning they are rewritten in the "machine" language of the central processing unit and then that machine code is executed), or interpreted (meaning they are converted to machine code line by line as they are executed).
3. JavaScript is of the interpreted type, and because it can also change parts of itself as it runs, it is called a "dynamic programming language"
4. HTML is your website content, CSS is how it should be styled, and JavaScript allows you to interact with the website in many ways.
5. Like CSS, JavaScript can be
internal, i.e. included in a <script> ... </script> element, or
external in a file with a .js file extension and referenced in HTML as <script src="my.java.js"></script>
6. The <script> element is placed either:
in the <head> element, or
just before the </body> closing tag.
7. Basic Javascript rules:
JavaScript is case-sensitive - This means a large character such as "A" is treated differently than a small character such as "a"
Whitespace is ignored (unless it is enclosed in quotes in a text string).
JavaScript is made up of a series of statements, commands that tell the browser what to do.
Single-line comments in JavaScript appear after two // characters:
// This is a single-line comment
Multiple-line comments go between /* and */ characters
8. JavaScript Statements
A script is made up of a series of statements.
A statement is a command that tells the browser what to do.
Here is a simple statement that makes the browser display an alert with the phrase “Thank you”:
alert("Thank you."); <---- The alert() method displays an alert box with a specified message and an OK button.
PRACTICE: https://www.w3schools.com/jsref/met_win_alert.asp
The semicolon at the end of the statement tells JavaScript that it’s the end of the command.
9. Variables - JavaScript variables are containers for storing data values . The keyword is var:
var years = 10; <------ the variable years is assigned a numeric value of 10
var total = price1 + price2; <----- doing simple addition
PRACTICE: https://www.w3schools.com/js/js_variables.asp
10. Variable name rules:
It must start with a letter, dollar sign, or underscore (no numbers or symbols).
It may not contain character spaces.
It can contain letters, digits, underscores, and dollar signs.
Names are case sensitive (y and Y are different variables).
Reserved words (like JavaScript keywords) cannot be used as names.
It may not contain special characters (! . , / \ + * =).
OPTIONAL: It could describe the information it contains (this is helpful).
11. Variable naming conventions - programmers often use certain methods of naming all their variables:
PascalPascal - two worded variables, each with a capital letter
camelCamel - two worded variables, but only the second work has a capital letter
years - all lower case
12. Variable data types:
Numbers - var length = 16;
Strings - var lastName = "Johnson";
Object - var x = {firstName:"John", lastName:"Doe"};
Arrays - var foo = [5, "five", "5"]; <---- note the square brackets
PRACTICENumbers, strings, and objects: https://www.w3schools.com/js/js_datatypes.asp
PRACTICE: Arrays: https://www.w3schools.com/js/js_arrays.asp
13. Accessing the Elements of an Array
You access an array element by referring to the index number.
For some strange, bizarre, and senseless reason, the first element of an array is number 0 (zero).
In this example of the array var foo = [5, "five", "5"]; , the value of foo[1] would equal "five".
PRACTICE: Arrays: https://www.w3schools.com/js/js_arrays.asp
14. JavaScript Operators assign values and perform arithmetic functions.
The assignment operator (=) assigns a value to a variable (there are many more types of assignment operators, see #15 below).
Arithmetic operators: + (add), - (subtract), * (multiply), and / (divide).
PRACTICE: https://www.w3schools.com/js/js_operators.asp
15. There are several types of assignment operators.
PRACTICE: https://www.w3schools.com/js/js_assignment.asp
16. Comparison operators evaluate and compare values.
One example is === which means: is identical to (equal to and of the same data type)
PRACTICE: https://www.w3schools.com/js/js_comparisons.asp
17. if/then statements:
An if/else statement tests for conditions by asking a true/false question.
if(true) { // Do something. }
i.e. if( 1 != 2 ) { alert("These values are not equal."); }
NOTE: The ! stands for not, so != means not (!) equal (=)
if(true) { // Do something. } else { // Do something else. }
In this exercise, you can get a feel for variables, arrays, and if/else statements by translating the statements written in English into lines of JavaScript code.
1. Create a variable called friends and assign it an array with four of your friends’ names.
HINT: Be sure to enclose each of your friends names in quotes.
2. Show the user a dialog that displays the third name in your list of friends.
HINT: Use the alert( ) function to display the name.
3. Create a variable called name and assign it a string value that is your first name.
4. If the value of name is identical to Jennifer, show the user a dialog box that says, “That’s my name too!”
HINT: The comparison operator === means is identical to (equal to and of the same data type).
5. Create a variable called myVariable and assign it a number value between 1 and 10. If myVariable is greater than five, show the user a dialog that says “upper.” If not, show the user a dialog that says “lower.”
The second half of this Chapter continues from the first part, illustrating more of the basic parts of JavaScript. After this introductory tour of JavaScript syntax (page 612), the remainder of the Chapter covers how JavaScript can manipulate the browser window, and how JavaScript can be used to "listen" for various events to occur such as the movement of the mouse pointer over an element on the page. On page 616 the text has two JavaScript examples.
1. Loops (pages 606-608) - Loops can execute a block of code as long as a specified condition is true.
PRACTICE: https://www.w3schools.com/js/js_loop_for.asp
PRACTICE: https://www.w3schools.com/js/js_loop_while.asp
2. Functions (pages 608-611)
Native Functions - built into JavaScript
Custom functions - functions you create
Arguments - the data that the function acts upon (i.e. adds two numbers)
Returning a value - the return keyword inside a function effectively turns that function into a variable with a dynamic value.
Example of returning a value: Suppose we have this JavaScript function:
function addNumbers(a,b) {
return a + b;
}
Any reference to that function gives you the result of that function, just like a variable would:
alert( addNumbers(2,5) ); // Alerts "7"
The addNumbers function is being used as a variable.
PRACTICE: https://www.w3schools.com/js/js_functions.asp
3. Variable Scope and the var Keyword (pages 611-612)
Scope refers to whether a variable is used throughout a JavaScript script (globally scoped) or is used only in a function it resides in (locally scoped).
The var keyword is used to specify of a variable is global or local:
Using var inside a function to define a variable to be used only inside that function:
var food = "value";
Do not use the var keyword if the variable inside a function is to be used globally: food = "value";
Using the var keyword outside of a function defines the variable as global.
PRACTICE: https://www.w3schools.com/js/js_scope.asp
4. The browser object - JavaScript also gives you access to and the ability to manipulate the parts of the browser window itself (pages 612-613).
PRACTICE: https://www.w3schools.com/js/js_ex_browser.asp
5. Events - An event is an action that can be detected with JavaScript, such as when the document loads, or when the user clicks on an element, or just moves her mouse over it (pages 613-615).
PRACTICE: https://www.w3schools.com/js/js_events.asp
EVEN MORE PRACTICE: https://www.w3schools.com/jsref/dom_obj_event.asp
Use the title.html document in your Chapter 21 Exercise Assignment folder.
1. Open title.html in a browser. You’ll see a blank page, with the title element already filled out. If you look up at the top of your browser window, in the tab, you’ll notice it reads “Million Dollar WebApp”:
2. Open title.html in your text editor. You’ll find a script element containing a comment just before the closing </body> tag. Feel free to delete the comment.
<!DOCTYPE html>
<html>
<head>
<title>Million Dollar WebApp</title>
</head>
<body>
<script>
// Your code goes here!
</script>
</body>
</html>
3. If we’re going to be changing the page’s title, we should save the original first. Create a variable named originalTitle. For its value, we’ll have the browser get the title of the document using the DOM method document.title. Now we have a saved reference to the page title at the time the page is loaded.
This variable should be global, so we’ll declare it outside of any functions.
var originalTitle = document.title;
<!DOCTYPE html>
<html>
<head>
<title>Million Dollar WebApp</title>
</head>
<body>
<script>
var originalTitle = document.title;
</script>
</body>
</html>
4. Next, we’ll define a function so we can reuse the script whenever it’s needed. Let’s call the function something easy to remember, so we know at a glance what it does when we encounter it in our code later. showUnreadCount() works for me, but you can name it whatever you’d like:
function showUnreadCount() { }
<!DOCTYPE html>
<html>
<head>
<title>Million Dollar WebApp</title>
</head>
<body>
<script>
var originalTitle = document.title;
function showUnreadCount() {
}
</script>
</body>
</html>
5. We need to think about what the function needs, to make it useful. This function does something with the unread message count, so its argument is a single number referred to as the variable unread in this example:
function showUnreadCount( unread ) { }
<!DOCTYPE html>
<html>
<head>
<title>Million Dollar WebApp</title>
</head>
<body>
<script>
var originalTitle = document.title;
function showUnreadCount( unread ) {
}
</script>
</body>
</html>
6. Now let’s add the code that runs for this function. We want the document title for the page to display the title of the document plus the number of unread messages. Sounds like a job for concatenation (+)!
NOTE: Concatenation is the process of linking things together in a series, i.e. "A" + "3" = "A3"
Here we set the document.title to be (=) whatever string was saved in the originalTitle variable (#3 above) plus the number in showUnreadCount. JavaScript combines (i.e. concatenates) a string and a number as though they are both strings.
document.title = originalTitle + unread;
Function methods are enclosed in curly brackets.
<!DOCTYPE html>
<html>
<head>
<title>Million Dollar WebApp</title>
</head>
<body>
<script>
var originalTitle = document.title;
function showUnreadCount( unread ) {
document.title = originalTitle + unread;
}
</script>
</body>
</html>
7. Let’s try out your script before we go too much further. Below where you defined the function and the originalTitle variable, enter showUnreadCount( 3 );
showUnreadCount(3);
<!DOCTYPE html>
<html>
<head>
<title>Million Dollar WebApp</title>
</head>
<body>
<script>
var originalTitle = document.title;
function showUnreadCount( unread ) {
document.title = originalTitle + unread;
}
showUnreadCount(3);
</script>
</body>
</html>
Now save title.html and reload it in your browser.
The title tag has changed! It’s not quite right yet, though:
8. Your script is working, but it’s not very easy to read. Fortunately, there’s no limit on the number of strings we can combine at once. Add new strings that wrap the count value and the words “new messages” in parentheses.
document.title = originalTitle + "(" + unread + " new messages!)";
<!DOCTYPE html>
<html>
<head>
<title>Million Dollar WebApp</title>
</head>
<body>
<script>
var originalTitle = document.title;
function showUnreadCount( unread ) {
document.title = originalTitle + " (" + unread + "new messages!)";
}
showUnreadCount(3);
</script>
</body>
</html>
Now save title.html and reload it in your browser.
The title tag is looking good!