Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
18 views

JavaScript Student Workbook.pdf

The document is a JavaScript Project Workbook that provides instructions for completing various coding assignments related to assignment and arithmetic operators, best practices, and script usage. It includes fill-in-the-blank exercises, project details, and step-by-step guidance for coding tasks. The workbook aims to help learners understand and apply JavaScript concepts effectively.

Uploaded by

ttvflashboy888
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
18 views

JavaScript Student Workbook.pdf

The document is a JavaScript Project Workbook that provides instructions for completing various coding assignments related to assignment and arithmetic operators, best practices, and script usage. It includes fill-in-the-blank exercises, project details, and step-by-step guidance for coding tasks. The workbook aims to help learners understand and apply JavaScript concepts effectively.

Uploaded by

ttvflashboy888
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 64

1| JavaScript Project Workbook

Fill-in-the-Blanks Domain 1
Instructions: While watching Domain 1, fill in the missing words according to the information presented
by the instructor.
[References are found in the brackets.]

Assignment and Arithmetic Operators

1. JavaScript has a sign which means, is this equal to this value? [Assignment]

2. In JavaScript, ++ means one to this. [Increment and Decrement]

3. With addition, the plus sign is used just as it is on a. [Addition]

4. When using JavaScript, your work after every one or two changes. [Subtraction]

5. When working with division in JavaScript, the remainder is otherwise known as the . [Division]

6. In JavaScript the method to control the number after the decimal point is. [Multiplication]

7. The modulus symbol in JavaScript is the symbol. [Modulus]

8. Compound assignment operators add, subtract, multiply, divide, and values at the same time.
[Compound Assignment Operators]

JavaScript Best Practices

9. Comments come in two forms: comments, and comments.


[Comments]

10. A JavaScript best practice is to indent inside of a single function.


[Indentations]

11. For naming conventions, casing is a JavaScript best practice. [Naming


Conventions]

12. are pop-up messages that appear in a web browser. [Noscript]


13. Variables can change throughout their use in code but cannot. [Constants]

14. In JavaScript, reserved keywords cannot be used to name a . [Reserved Keywords]

in progress. [Debugger
15. You can use the debugger keyword to stop the Keyword]
16. Breakpoints allow you to code, check on variables, and then run code step by step to continue
processing it. [Set Breakpoints]

17. You will often have as a debugging tool a console in which you can enter to get information.
[Console.log]

Inline and External Scripts

18. Like style sheets, are better managed when they are external. [When to Use]

3 | Domain 1 JavaScript Project Workbook


19. As a best practice, JavaScript scripts should be placed into a folder. [How to Use]

20. Anything used on an style sheet should not be repeated inline. [Use Both Scripts]
Exception Handling
21. One unique aspect of JavaScript is messages do not typically pop up in a web
that they occur. [Try and Catch] browser when

22. A finally block will run no matter which part, or , runs. [Finally]
Browser Object Model Interaction

23. With HTML, CSS, and JavaScript, applications are built with many
opportunities for . [Manage
State]

24. Alerts are basically displayers and have an OK button. [Display Dialogs]

25. is a browser object and width and height are two of its properties.
[Determine Screen Size]

Using Assignment, Project Details

Increment, and Decrement Project File:


11a-cartassignments.htm

Operators Estimated
One of the most important aspects to understand about JavaScript is Completion Time:
minutes
the proper use of operators. The first two projects in this workbook will
cover some of these operators in detail. The first three operators you
will work with are the assignment, increment, and decrement operators. Video Reference:
Increment operators tell a variable to increase by one and decrement Domain 1
operators tell a variable to decrease by one. Topic: Assignment and
Arithmetic
Operators
Note: For all projects in this course, when you are asked to open a file,
Subtopics: Assignment;
assume you need to open it in your code editor unless you see a Increment and Decrement
different specification, like opening the file in your web browser.
Objectives Covered:
Purpose: 1 JavaScript Operators,
After completing this project, you will know how to use assignment, Methods, and
increment, and decrement operators. Keywords
1.1 Complete and debug
code that uses assignment
Steps for Completion: and arithmetic operators
1. Open the 11a-cartassignments.htm file from the Music1 Student 1.1.a 1.a Assignment
folder to your code editor. 1.1.b 1.b Increment
2. Find this comment: <!-- Add the three operators for the three input 1.1.c Decrement
buttons--> approximately 60 lines down in the document.
3. Find the three input buttons with IDs of manqtyadd, manqtysub, and manqty zero,
respectively.
4. On the line with the button with the ID of manqtyadd, add the increment operator to
the value property.
5. On the line with the button with the ID of manqtysub, add the decrement operator to
the value property.

4 | Domain 1 JavaScript Project Workbook


6. On the line with the button with the ID of manqtyadd, add the necessary operator
and value to set the manqty element to 0.
7. Save your changes.
8. Preview the webpage in a web browser. You should be able to click the +, -, and 0
buttons and have the value in the text box increase by one, decrease by one, and
reset to 0 respectively. (COPY CODE FROM THE VIDEO)

Addition and Subtraction Project Details

JavaScript, like many other programming languages, uses the computer Project Files:
standard of a + for addition, a – for subtraction, a * for multiplication, 11d-cart-operators.htm
and a / for division. The key point of knowledge for the exam is to know
which operators to use given a situation or problem to solve. That is Estimated Completion
exactly what you will practice in this and the next project. Time:
minutes
Purpose:
After completing this project, you will be able to identify which Video Reference:
operators to use in a given situation. Domain 1
Topic: Assignment and Arithmetic
Steps for Completion: Operators
Subtopics: Addition;
1. Open the 11d-cart-operators.htm file from the Music1 Student
Subtraction; Multiplication
folder in a web browser.
2. Take note of what needs to be added to get to a subtotal and then
subtracted to get to a grand total. Objectives Covered:
1 JavaScript Operators, Methods,
3. Open the 11d-cart-operators.htm file from the Music1 Student and
folder in your code editor. Keywords
4. Find this comment: <!-- Add the addition and subtraction operators 1.1 Complete and debug code
that uses assignment and
in the correct places --> arithmetic operators
5. Add addition operators and subtraction operators in the correct 1.1.d Addition
places in the Update Cart button script to get the correct subtotal 1.1.e 1.e Subtraction
and grandtotal, ignoring the sales tax for now.
6. Save your changes.
7. Preview the webpage in a web browser. Project Details
8. Click the Update Cart button. You should see a total of 799.97.
Project Files:
Multiplication, Division, and 11f-soundproofing.htm

Modulus Operators Estimated Completion


Time:
minutes
The next three operators we are going to look at in some detail are the
multiplication operator, which is a * in computing terms, division
operator, which is a / in computing terms, and the modulus. A modulus, Video Reference:
as indicated by a %, indicates a remainder. For example, in terms of Domain 1
integers, 10/3=3. 10%3=1. Why? 10/3=3 with a remainder of 1. That 1 Topic: Assignment and Arithmetic
is the modulus. You need to know this for the exam and you will need Operators
this in real life for when you need to calculate a remainder, as you will Subtopic: Multiplication;
Division; Modulus
do in this project, which calculates the number of pieces needed for
soundproofing a room at 25 square feet per piece.
Objectives Covered:
Purpose: 1 JavaScript Operators, Methods,
and
Upon completing this project, you will know how and when to use the Keywords
multiplication, division, and modulus operators. 1.1 Complete and debug code
that uses assignment and
5 | Domain 1 JavaScriptoperators
arithmetic Project Workbook
1.1.f 1.f Division
1.1.g 1.g Multiplication
1.1.h 1.h Modulus
Steps for Completion:
1. Open the 11f-soundproofing.htm file from the Music1 Student folder.
2. Look for this comment about 45 lines down the document: <!-- Three operators needed below -->
3. Over the next seven lines, there are three // that need replacing with the proper operators. Replace
them with the correct operators so that the following takes place:
a. The correct number of pieces needed are calculated given that each piece covers 25 square feet.
b. The number of square feet for the final piece is indicated.
c. The total cost, given each piece sells for $20, is displayed.
4. Save your changes.
5. Preview the file in a web browser.
6. Click in the Enter the Square Footage field.
7. Type: 460
8. Click the Calculate button. If you get a message saying you need 19 pieces and there will be 10
square feet left and that the total cost is $380, congratulations. If not, go back and look at the logic
you used for the operators and try again.

Compound Assignment Project Details

Project Files:
Operators 11i-cart-compound.htm

Compound assignment operators can add, subtract, multiply, divide,


and update values at the same time. Take, for example, this equation: x
Estimated Completion
= x+5. With a compound operator, that same equation can be written Time:
this way: x += 5. Compound operators -=, *=, and /= subtract, minutes
multiply, and divide values, respectively.
Video Reference:
Purpose: Domain 1
After completing this project, you will know how to use a compound Topic: Assignment and Arithmetic
Operators
operator to update a value.
Subtopic: Compound
Assignment Operators
Steps for Completion:
1. Open the 11i-cart-compound.htm file in your Music1 Student Objectives Covered:
folder to your code editor. 1 JavaScript Operators, Methods,
2. Scroll to the bottom of the page and find the <script> section. and
Keywords
3. Within the script, find the // add five comment.
1.1 Complete and debug code
4. Replace the // add five comment with a compound operator that uses assignment and
assignment to add five to the newQty variable. arithmetic operators
5. Replace the // subtract five comment with a compound operator Compound assignment
operators (+=, -=, *=, /=,
assignment to subtract five from the newQty variable.
%=)
6. Save your changes.
7. Preview the file in a web browser.
8. Click the Add Five button. It should add five to the quantity amount for the mandolin.
9. Click the Subtract Five button. It should subtract five from the quantity amount for the mandolin.
10. Close your open files in both your web browser and code editor.

6 | Domain 1 JavaScript Project Workbook


Comments, Indentations, Project Details

Project Files:
and Naming Conventions 12a-soundproofing.htm

Part of writing good code in any programming language is to make the


code readable, consistent, and, as much as possible, easy for someone
Estimated Completion
else reading the code to discern what is going on with the code. To that Time:
10-15 minutes
end, we should add comments to code when it becomes necessary to
explain what is going on in code. A // within a script indicates a single-
line comment. Text within /* and */ symbols indicate a multiline Video Reference:
comment. Domain 1
Topic: JavaScript Best Practices
Code inside of functions, if statements, and similar methods should be Subtopics: Comments;
Indentations; Naming
indented, so that one can easily understand which code block is inside Conventions
of which statement. In addition, when naming objects in JavaScript, the
usual best practice is to use camel casing. Camel casing involves a
lowercase first word and then the capitalization of the first letter of Objectives Covered:
each subsequent work in an object. For example, a variable named total 1 JavaScript Operators, Methods,
and
quantity could be named as totalQty or totalQuantity using camel
Keywords
casing. 1.2 Apply JavaScript best
practices
Purpose: 1.2.a 2.a Comments
After completing this project, you will know how to implement 1.2.b 2.b Indentations
comments, indentations, and naming conventions within JavaScript 1.2.c Naming
code. conventions

Steps for Completion:


1. Open the 12a-soundproofing.htm file from your Music1 Student folder.
2. Scroll down about 45 lines to find this code: <!-- Code cleanup needed in the next
paragraph -->
3. Between the <p> and </p> tags below the comment, indent the code so that it is even
and readable.
4. Click in the blank line above this code: document.getElementById(‘sqftremaining’).
innerHTML = ‘The last piece will take up ‘ + parseInt(document.
getElementById(‘sqft’).value % 25) + ‘ square feet.’;
5. Add a single-line comment explaining that the modulus operator is being used in the
line below.
6. On the line below where you just added the comment, rename the sqftremaining object
to use camel casing.
7. Find the code <p id=”sqftremaining”> several lines below the current line.
8. Rename the sqftremaining object to use the same camel casing you used in Step 6.
9. Save your changes.
10. Preview the webpage in a browser.
11. To make sure the webpage still works, click in the Enter the square footage field and
type 490
12. Click the Calculate button. You should see that 20 pieces are needed, and 15 square
feet will remain.

7 | Domain 1 JavaScript Project Workbook


Using Script and Noscript Project Details

Project Files:
Tags 12d-tuningkits.htm

As we continue learning the basics of JavaScript code, we want to know


when to use a script and a noscript tag. Script tags are used to hold
Estimated Completion
JavaScript code and keep it away from HTML code on a webpage. As an Time:
minutes
example, functions are often defined within script tags and then called
from elsewhere on a webpage.
Video Reference:
A noscript tag has one purpose: to alert a user that the browser being Domain 1
used does not support JavaScript. This could stem from a very old Topic: JavaScript Best Practices
browser being in use, but more likely the cause is a browser that has Subtopic: Noscript
JavaScript disabled. Either way, we want to let a user know when
JavaScript is not working. The noscript tag accomplishes that. Objectives Covered:
1 JavaScript Operators, Methods,
and
Purpose: Keywords
After completing this project, you will know how to utilize the script and 1.2 Apply JavaScript
noscript tags within a webpage. best practices
Noscript
Steps for Completion:
1. Open the 12d-tuningkits.htm file from your Music1 Student folder.
2. Scroll to the end of the document.
3. Click on a blank line just inside the closing body tag.
4. Add an opening and closing script tag.
5. Within the new script tag, add an alert with the text, Your browser supports JavaScript
6. Below the closing script tag, add an opening and closing noscript tag.
7. Within the noscript tag, add this text, Your browser does not support JavaScript
8. Save your changes.
9. Preview the file in a web browser. Either you will see that your
browser supports JavaScript, or, you will see that it does not support Project Details
JavaScript.
Project Files:
Constants and Reserved 12e-cart-constants.htm

Keywords Estimated Completion


Time:
Variables, which are containers that store information that we can reuse minutes
in code, will be covered in detail later in this course. One type of
variable we will cover now, though, is that of a constant. A constant is a
variable that cannot have its value changed once it is set. This is helpful Video Reference:
Domain 1
for when you want to use something such as a rate for calculations
Topic: JavaScript Best Practices
throughout a webpage.
Subtopics: Constants;
Reserved Keywords
When building variables, functions, or anything else with a name, you
will want to avoid using reserved keywords, that is, keywords already in
use in JavaScript, as an object name. Pay attention to keywords you see
Objectives Covered:
1 JavaScript Operators, Methods,
in use throughout this course as you could be asked on the exam which and
words are keywords and which ones are not. Keywords
1.2 Apply JavaScript
best practices
1.2.e 2.e
8 | Domain 1 JavaScript ProjectConstants
Workbook
1.2.f 2.f
Reserved
keywords
Purpose:
After completing this project, you will know how to declare constants and you will know some of the more
prevalent reserved keywords in JavaScript.

Steps for Completion:


1. Open the 12e-cart-constants.htm file from the Music1 Student folder.
2. Scroll down to the end of the document.
3. On the line before the closing body tag, add an opening and closing script tag.
4. Within the new script tag, create a blank line if necessary.
5. On the blank line, within the script tag, add a constant variable named salesTaxRate and set the
value to .07
6. Scroll up and find the following code: <!-- sales tax rate constant goes in this area -->
7. Look several lines below the comment. Find this code: document.
getElementById(‘salesTax’).innerHTML = parseFloat(document.
getElementById(‘subtotal’).innerHTML * .07).toFixed(2);
8. In the code you just found, replace the .07 value with the new salesTaxRate constant.
9. Save your changes.
10. Preview the page in a web browser.
11. Click the Update Cart button. Your total should be 856.67.
12. For each declaration of a variable, indicate whether the declaration is valid or invalid due to the use
of a reserved keyword:
a. stepOne = “Sign up for a class.”
b. function = “Sign up for a class”
c. void = null
d. emptySet = null

The Debugger Keyword Project Details

Part of writing good code is knowing the tools you have to troubleshoot Project File:
code and using those tools well. JavaScript does not have as many 12g-cart-constants.htm
troubleshooting tools as do other languages, but, there are still a few
good ones you can use, mostly within a web browser. If your code editor Estimated Completion
has troubleshooting tools, you can use those as well. One common Time:
troubleshooting tool to use is the debugger keyword. This will make the minutes
code pause at that point and then, within a browser, you can use the
console within the browser to run tests on current variables and HTML
elements. Video Reference:
Domain 1
Topic: JavaScript Best Practices
Purpose: Subtopic: Debugger Keyword
After completing this project, you will have familiarity with the debugger
statement and know how to use it within a webpage.
Objectives Covered:
1 JavaScript Operators, Methods,
Steps for Completion: and
1. Open the 12g-cart-constants.htm file from the Music1 Student Keywords
folder. 1.2 Apply JavaScript
best practices
2. Scroll down about 175 lines to this code: // put the debugger here
2.g Debugger keyword
3. Replace the comment and code with the debugger keyword.
4. Save your changes.
5. Preview the webpage in a web browser.

9 | Domain 1 JavaScript Project Workbook


6. Press the F12 key to open a console window.
7. Click the Update Cart button. The code will pause at the point of the debugger and the console will
appear.
8. Type: document.getElementById(‘subtotal’).innerHTML
9. Press the Enter key. You should see a total of 809.97.
10. Find the Play symbol in the debugger and click it. The code will finish running.

Using Breakpoints and Project Details

Console.log Project File:


12h-cart-constants.htm
While the debugger statement is useful when you always want a
breakpoint in code, you may want to apply breakpoints as code is
running in the browser.This can be done on webpages that await user Estimated
interaction, like the click of a button.You can use the console to insert Completion Time:
breakpoints and then use those breakpoints to test values within a minutes
webpage.
Video Reference:
The console.log feature allows you to type elements and variables Domain 1
Purpose
within the console and receive a return of the value of the element or Topic: JavaScript Best
:variable you type. Practices
Subtopic: Debugger
Keyword; Set Breakpoints;
Console.log
After completing this project, you will know how to use breakpoints and
1the console.log statement. Note that the steps will vary based on the
Objectives Covered:
.2browser you are using.
1 JavaScript Operators, Methods,
.3 and
.4Steps for Completion: Keywords
.5 Open the 12h-cart-constants.htm file from the Music1 Student 1.2 Apply JavaScript best
.6 folder. practices
1.2.h 2.h Setting
.7 Preview the webpage in a web browser. breakpoints
.8 Press the F12 key to open a console window. 1.2.iConsole.log
.9 In the Sources area, select the file.
. Expand the Event Listener Breakpoints area.
Expand the Mouse area.
Select the click checkbox.
Click the Update Cart button.
Notice, in the debugger, the Watches window. Scroll through the
earlier
. Watches window to see values for the HTML elements on the
page.
10.should
Play the
be rest of the code.
undefine
11.Ste
15 Refresh d.the
intoth webpage.
code
.12.pClick the
e .Update Cart button.The code should stop at the breakpoint you added

13. Click the Console tab.


14. Type a console.log statement for the innerHTML value of the subtotal element. It

16. Rerun the console.log statement you typed earlier. It should show a value of 809.97.
17. Close all your open webpages in your browser and files inside of your code editor.

10 | Domain 1 JavaScript Project Workbook


JavaScript Project Workbook

The Use of Inline and Project Details

Project Files:
External Scripts 13a-cart-compound.htm
main.js
When building scripts with JavaScript code (or any script for that
matter), one important decision to make is whether to put the script
Estimated Completion
inline, meaning inside of a file, or in an external file. You also, both for
the exam and beyond, will want to know the effects of having both
Time:
10-15 minutes
inline and external scripts, especially when the same variable name is
declared in both files.
Video Reference:
Domain 1
Purpose: Topic: Inline and External Scripts
After completing this project, you will have a better understanding of Subtopics: When to Use;
when to use scripts inline and when to use external scripts. You will also How to Use; Use Both Scripts
know how variables behave when they are declared in both inline and
external scripts.
Objectives Covered:
1 JavaScript Operators, Methods,
Steps for Completion: and
1. Open the 13a-cart-compound.htm file from the Music1 Student Keywords
folder in a web browser. 1.3 Evaluate the use of
internal and external scripts
2. View the HTML source of the file. Is the JavaScript code inline or in an external file? 3.a When to use
1.3.a
1.3.b 3.b How to use
3. Give two reasons in favor of using external scripts over inline scripts: 1.3.c What happens
when scripts are used at
4. Click the Update Cart button. The total amount should be 856.67. multiple levels

5. In your code editor, open the 13-cart-compound.htm file and the main.js files from your Music 1
Student folder.
6. Notice the salesTaxRate of .075 within the main.js file.
7. Return to the 13-cart-compound.htm file and scroll to the script tag at the bottom of the page.
8. Notice the salesTaxRate of .07. This is the rate used in the calculation to create a total amount of
856.67.
9. In the head section, add a tag that links the current page to the
main.js file in the scripts folder. Project Details
10. Save your changes.
11. Preview the webpage in a web browser. Project Files:
14a-practice.htm
12. Click the Update Cart button. What is the total amount?

Estimated Completion
13. What caused the amount to change?
Time:
Implementing Exception minutes

Video Reference:
Handling Domain 1
Topic: Exception Handling
Exceptions are errors that happen while code is running. Unless handled
Subtopic: Try and Catch; Finally
properly, exceptions will usually cause an app to crash. To handle these
exceptions more gracefully, code that could fail during runtime should
be implemented using a try/catch/finally block, to where the try block Objectives Covered:
contains the code one attempts to run, the catch block runs if the code 1 JavaScript Operators, Methods,
and
Keywords
1.4 Implement
11 | Domain 1 JavaScriptexception
Project Workbook
handling
1.4.a 4.a Try
1.4.b 4.b Catch
1.4.c Finally
in the try block causes an exception, and the finally block contains code that runs whether the try block
worked or did not work.

Purpose:
After completing this project, you will know how to use the try, catch, and finally keywords in JavaScript
code.

Steps for Completion:


1. Open the 14a-practice.htm file from your Music1 Student folder.
2. Locate the script tag about 20 lines down the page.
3. In the script tag, wrap the current function inside of a try block.
4. Below the try block, add a catch block that will catch any possible error in the code and, if there is an
error, display an alert with the message, Error:, plus the error’s description.
5. Below the catch block, add a finally block that displays an alert with the message, Thank you for
visiting our site
6. Save your changes.
7. Preview the webpage in a web browser.
8. Enter a number amount in the available text field.
9. Press the Tab key. You should see an error message stating that something is undefined and the thank
you message for visiting the site.
10. Return to your code editor.
11. Within the try block, change the text document.getElementByID to document.
getElementById as ID is the improper casing for the getElementById
method.
12. Save your changes.
13. Refresh the webpage in the web browser.
14. Enter a number amount in the available text field.
15. Press the Tab key. You should see a calculation on-screen and the thank you message for visiting the
site.

Managing States Project Details

A state of a JavaScript object describes the current mode of an object. Project Files:
Windows can be open or closed. Objects can be made to be visible or 15a-cart-checkout.htm
invisible. Buttons can be enabled or disabled. For the exam, make sure
you understand the meaning of a state of an object. Estimated
In the upcoming project, you will get a small sample of managing Completion Time:
states. minutes

Purpose: Video Reference:


After completing this project, you will have a better understanding of Domain 1
the concept of managing states for JavaScript objects. Topic: Browser Object
Model
Interaction
Steps for Completion:
Subtopic: Manage State
1. Open the 15a-cart-checkout.htm file from the Music1 Student
folder.
2. Scroll down to the script tag near the bottom of the document and Objectives Covered:
1 JavaScript Operators,
find this code: // Close the checkWin window here
Methods, and
3. Replace the code and the comment with code to close the checkWin Keywords
window. 1.5 Complete and debug
code that interacts with the
4. Save your changes.
Browser Object
Model (BOM)
12 | Domain 1 JavaScript Project Workbook
5.a Display dialogs
5. Preview the webpage in a web browser.
6. Click the Checkout button. A new, small browser window will open. This window is now in the open
state.
7. Click the Close Checkout button. The small window will close,
putting the window in the closed state. Project Details

Display Dialogs Project Files:


15b-cart-welcome.htm
Dialog boxes can capture user input, help a user confirm a step made
on a webpage, or display an alert either for training purposes or when
an error occurs. Specifically, there are three types of dialog boxes you Estimated
need to know about for the exam: Completion Time:
minutes
Alert: displays a pop-up message on the screen. This does not take
user interaction, except for displaying an OK button.
Confirm: an alert-like dialog with an OK and a Cancel button. Action Video Reference:
can be coded based on which button a user clicks. Domain 1
Topic: Browser Object
Prompt: a dialog which accepts user input. This input is usually
Model
then stored in a variable. Interaction
Subtopic: Display Dialogs
Purpose:
After completing this project, you will know which display dialog to use Objectives Covered:
in given situations. 1 JavaScript Operators,
Methods, and
Steps for Completion: Keywords
1. Open the 15b-cart-welcome.htm file from your Music1 Student 1.5 Complete and debug
code that interacts with the
folder. Browser Object
2. Scroll down to the script tag near the bottom of the document. Look Model (BOM)
for this comment: // enter the alert, confirm, and prompt keywords 5.a Display dialogs
to replace the comments in the welcome function
3. Within the welcome function, there are three comment symbols. Replace each of the comment
symbols with the correct type of display dialog (alert, confirm, or prompt), using the code as your
guide. Each display dialog will be used once.
4. Save your changes.
5. Preview the webpage in a web browser. Project Details
6. Enter your name in the prompt dialog box.
7. Click the OK button.
Project File:
15c-screensize.htm
8. Click the OK button again to confirm your name.
9. Click the OK button to close the alert.
Estimated

Determining Screen Size Completion Time:


minutes
The final project in this domain will cover the code necessary to display
the screen width and the screen height. This could be important Video Reference:
information to know for developing an app as you may want to, for Domain 1
example, change a style sheet being used based on a screen size. The Topic: Browser Object Model
screen width and height are both properties of the screen object. Interaction
Subtopic: Determine
Screen Size
Purpose:
Objectives Covered:
1 JavaScript Operators,
Methods, and
Keywords
1.5 Complete and debug
13 | Domain 1 JavaScript
code Projectwith
that interacts Workbook
the
Browser Object
Model (BOM)
5.b Determine screen size
After completing this project, you will know how to obtain the screen width and screen height through
JavaScript.

Steps for Completion:


1. Open the 15c-screensize.htm file from the Music1 Student folder.
2. Find the body tag, located about eight lines down in the file.
3. In the alert method for the onload event, enter the code necessary to display the screen width and
the screen height, along with text describing the screen width and screen height.
4. Save your changes.
5. Preview the webpage in a web browser. You should see a message similar to the following:
6. Click the OK button.
7. Restore your browser to a different size.

8. Refresh the webpage. Does the screen size change?


9. Close your open files in both your web browser and in your code editor.

14 | Domain 1 JavaScript Project Workbook


Fill-in-the-Blanks Domain 2
Instructions: While watching Domain 2, fill in the missing words according to the information presented by
the instructor.
[References are found in the brackets.]

Primitive Data Types

1. A is a container used to hold information. [Number]

2. Boolean variables store two possibilities: or . [Boolean]

3. Strings are variables that can store pretty much . [String]

4. Null means , not zero. [Null]

5. An undefined variable is one that has been , but has never had a value. [Undefined]

6. If you have a variable that is not acting the way you think it should, check out its . [Typeof Operator]

7. Any number variable is a decimal in JavaScript. [Type Checking Functions]

8. The keyword tells JavaScript this is a variable and not an object. [Use Strict]

9. In many cases, a data type has to be explicitly before it can be used. [Convert Between Data Types]

10. One common wish in JavaScript is to convert a number to . [Format Numbers]

11. JavaScript has many different ways in which strings can be . [String Operations]

12. One area that JavaScript is not that picky about is in the use of marks. [Nesting Quotes]
13. If you know what a variable should when you declare it, initialize it. [Initialization]

Declare and Use Arrays


14. Think of an array as having but with multiple sections, with each section storing
a items. [Build and Define one or more
an Array]
15. When working with an array, you may want to show one item at a time in the
form of a .
[Iteration and Length]

16. Arrays that are coded but not filled in are considered . [Initialization]

17. The is a great way to experiment with array features. [Sorting and
Searching]

18. adds an item to an array while removes the last item from an array.
[Push and Pop]

19. Shift really is the opposite of , and unshift really is the opposite of
.

16 | Domain 2 JavaScript Project Workbook


[Shift and Unshift]

20. The first item in an array has an index number of . [Access an


Element]
21. The called multiArray starts a new array. [Understand Multi-Dimensional
Arrays]

Complete and Debug Code on Objects

22. Objects are things we can . [Properties]

23. Methods all have at the end of them. [Methods]

24. Having classes objects helps ensure consistency among objects. [Instantiation]

25. A date variable with no date specified will return the date. [Date Object and Time]

26. JavaScript uses numbers through as month numbers. [Retrieving


Date Parts]

27. The code needed to convert a date into US format is . [Localization]

28. When we subtract two dates in JavaScript, the difference appears in . [Add and Subtract Dates]

Built-In Math Functions

29. In JavaScript, a is an escape character. [Random]

30. The round method in JavaScript rounds a number to the nearest number. [Round]

31. The Math.abs method in JavaScript will make a number represent its value. [Abs]

32. The floor method takes the lower whole number of two numbers around a . [Floor and Ceiling]

33. The min and max functions retrieve minimum and maximum numbers from a of numbers. [Min and
Max]

34. The Math.pow method in JavaScript takes a number and it to the power specified. [Pow]

35. The Math.sqrt method takes a number and calculates its [Sqrt]

Parameters and Return Values

36. help to create reusable code. [Reusable Code]

37. The best way to test variable scope is to use the . [Local vs. Global Scope]

38. are the type of variable that cannot be redefined. [Redefining Variables]
39. When declaring a variable for use as a parameter, for the variable must be specified.
the Parameters] [Passing

40. For objects, it is better to set each object to have its own . [Value vs. Reference]
41. If a result is saved for later use, the return keyword is used. [Return Values]

17 | Domain 2 JavaScript Project Workbook


Number, Boolean, and Project Details

Project Files:
String Variables 21a-cart-variables.htm

A variable is one of the most important components of any


programming language. A variable is a container that stores
Estimated Completion
information, with the presumption that the variable will be used one or Time:
minutes
more times within a block of code. For example, if one must use the
same sales tax rate five times within code, which option is better:
entering the number five times, or storing that number in a variable Video Reference:
once and then using that variable five times? Most would say the latter. Domain 2
Topic: Primitive Data Types
There are two aspects of data types you need to know about for the Subtopic: Number; Boolean;
String
exam. First, variables have some naming rules. They can’t have spaces
and they cannot start with a number. They can have underscores and
dollar signs. Variable names are case sensitive as well. For example, a Objectives Covered:
variable named salestax is different from one named salesTax (the 2 Variables, Data Types, and
preferred camel casing) and different from one named SalesTax. Also, Functions
JavaScript is a loosely typed language, meaning that one does not need 2.1 Declare and use variables
of primitive data types
to specify a data type (like a number or string) when declaring a
2.1.a 1.a Number
variable. JavaScript will look at the data and assign a data type
2.1.b 1.b Boolean
accordingly.
2.1.c String

The three variables you will declare in this project are number variables, string variables, which hold text,
and Boolean variables, which are set to either true or false.

Purpose:
After completing this project, you will know how to name variables
properly and you will know how to declare number, Boolean, and string
variables.

Steps for Completion:


1. For each variable listed, indicate whether the variable name is valid or invalid:
a. checkOut:
b. check Out:
c. $check_Out:
d. 2checkOut:
e. checkOut2:
2. Open the 21a-cart-variables.htm file from the Music2 Student folder.
3. Scroll down to the script tag near the end of the document. You will see three commented lines.
4. Replace the text in the first commented line with a variable declaration setting a variable named
discount set to a value of 10
5. Replace the text in the second comment line with a variable declaration setting a variable named
checkOutExists set to a value of false
6. Replace the text in the third comment line with a variable declaration setting a variable named
checkOutPage set to the text, checkout.htm
7. Save your changes.
8. Preview the webpage in a web browser.
9. Click the Update Cart button. The total amount should be 860.72.
10. Click the Checkout button. A new window should open.

18 | Domain 2 JavaScript Project Workbook


11. Click the Close Checkout button. The window opened in the previous step should close.

Null and Undefined Project Details


Vari
Variables of all types (number, Boolean, string, dates, and others) can Project File:
be set to null or be left undefined. Here is the difference between the 21d-cart-variables.htm
two: setting a variable to null makes it empty. This, however,
presupposes that a variable had a value in the first place. An undefined Estimated Completion
variable is one that is declared but never has a value assigned to it. It is Time:
important to be able to distinguish the two states of null and undefined minutes
for the exam and beyond.

Video Reference:
In addition, you will sometimes want to declare variables using the var Domain 2
keyword. While this is not required, using var tells JavaScript that Topic: Primitive Data Types
indeed you are declaring a variable and not a new object. The less Subtopics: Null; Undefined
thinking JavaScript must do, the faster apps run.

Objectives Covered:
Purpose: 2 Variables, Data Types, and
After completing this project, you will be able to set a variable to null Functions
and set a variable to be undefined. 2.1 Declare and use variables
of primitive data types
2.1.d Null
Steps for Completion:
2.1.e 1.e Undefined
1. Open the 21d-cart-variables.htm file from the Music2 Student
folder in a web browser.
2. In the Mandolin field, click the + button to add one to the quantity.
3. Click the Clear button. Notice the quantity does not clear but changes to 0.
4. To start to fix the code, open the 21d-cart-variables.htm file in your code editor.
5. Scroll down about 65 to 70 lines to find this comment: <!--make the manqty field empty when the
Clear button is clicked-->
6. A few lines below the comment, for the button with the ID, manqtyzero, change the code so that the
manqty field becomes empty and not 0 when the button is clicked.
7. Scroll down to the bottom of the document.
8. Within the script tag, replace the comment with two variable Project Details
declarations: subtotal and grandTotal. Both should be declared as
undefined variables. Project Files:
9. Save your changes. 21f-cart-variables.htm
10. Preview the webpage in a web browser.
11. In the mandolin area, click the + button to increase the quantity by Estimated
one. Completion Time:
12. Click the Clear button. The quantity should now be empty. minutes

Type of Operators and Type Video Reference:


Domain 2

Checking Functions Topic: Primitive Data Types


Subtopic: TypeOf
When working through JavaScript code, you sometimes will need to Operator; Type Checking
Functions
check to see what data type is assigned to a variable. This is necessary
because JavaScript is a loosely typed language, meaning data types are
not explicitly assigned to variables. Rather, the data type is assigned Objectives Covered:
when the variable receives a value. The typeof function, whether used 2 Variables, Data Types, and
in code or in a web browser’s console, indicates the data type of a Functions
variable. 2.1 Declare and use
variables of primitive data
types
2.1.f 1.f Type
of operator
19 | Domain 2 JavaScript
2.1.g Project1.gWorkbook
Type
checking
functions
Similar to the typeof function, there are several other functions that can check to see if a
variable has the anticipated data type. As an example, the Number.isInteger function checks to see if a
variable is an integer.

Purpose:
After completing this project, you will know how to use the typeof function and type checking functions in
JavaScript.

Steps for Completion:


1. Open the 21f-cart-variables.htm file from the Music2 Student folder.
2. Scroll down to the bottom of the page and locate the script tag. There are three variables you will use
to check properties: discount, checkOutExists, and checkOutPage.
3. Preview the webpage in a web browser.
4. Press the F12 key to bring up the console. If necessary, click the Console tab.
5. In the Console tab, use the typeof function to identify the type for the checkOutExists variable. Which
type is it?

6. Which variable type is the checkOutPage variable?

7. Is the discount variable an integer?

The Use Strict Phrase Project Details

In an earlier project, we mentioned that the var keyword in front of a Project Files:
variable declaration tells JavaScript that the variable is indeed a 21h-practice-strict.htm
variable and not an object. Using the var keyword in front of a variable
also makes it easier for someone reading code to tell a variable apart Estimated
from an object. Completion Time:
minutes
To enforce the use of the var keyword, the phrase, use strict, can be
added within a script or a function. Video Reference:
Domain 2
Purpose: Topic: Primitive Data
After completing this project, you will know how to use the phrase, use Types Subtopic: Use
strict, to force all variables to be declared with the var keyword. Strict

Steps for Completion: Objectives


1. Open the 21h-practice-strict.htm file from your Music2 Student Covered:
folder. 2 Variables, Data Types,
2. Locate the script tag and the getPracticeHours function at the and
Functions
bottom of the page.
2.1 Declare and use
3. Add a blank line just after the getPracticeHours function declaration. variables of primitive data
types
4. Add the phrase, use strict, with appropriate punctuation, to the
1.h Use strict
blank line.
5. Save your changes.
6. Preview the webpage in a web browser.
7. Enter a number in the hours field.
8. Press the Enter key. What happened?

9. Go back and look at the code in your code editor.


Why did the webpage exhibit the behavior it just did?

20 | Domain 2 JavaScript Project Workbook


10. Fix the cause of the error.
11. Save your changes.
12. Preview the webpage in a web browser.
13. Enter a number in the hours field.
14. Press the Enter key. The webpage should now work.

Converting Between Data Project Details

Project Files:
Types 21i-cart-operators.htm

When input fields are created on an HTML form, they are objects in the
Estimated Completion
eyes of JavaScript. Many of these fields eventually contain numbers
used in a calculation. The only problem with this is that because these Time:
minutes
are objects, they cannot be used in calculations unless they are
converted to a number, like an integer or a floating decimal. This is just
one of many examples of data type conversions that can become Video Reference:
necessary on occasion in JavaScript. Domain 2
Topic: Primitive Data Types
Subtopic: Convert Between
Purpose: Data Types
After completing this project, you will have a better understanding of
when data type conversions are needed and how to perform those
conversions. Objectives Covered:
2 Variables, Data Types, and
Functions
Steps for Completion: 2.1 Declare and use variables
1. Open the 21i-cart-operators.htm file from the Music2 Student of primitive data types
folder in a web browser. Converting between data
types
2. Press the F12 key to bring up the console. (parseInt, parseFloat)
3. In the console, type:
typeof(document.getElementById(‘mantotal’))

4. Press the Enter key. Is this an object or a variable?


5. Open the 21i-cart-operators.htm file in your code editor.
6. Scroll down until you see this comment: <!-- replace comments with the command necessary to make
these values decimals -->
7. Within the orderbuttons div class, replace each comment with the built-in function used to convert an
object into a decimal field.
8. Save your changes.
9. Preview the webpage in a web browser. Project Details
10. Click the Update Cart button. Do not worry about the floating
decimal as you will fix that in the next project. Project File:

Formatting Numbers
21j-formatting-numbers.htm

One of the most common needs for displaying data in JavaScript is the Estimated Completion
need to format numbers, especially those with a float data type. Time:
Floating numbers tend to display more places after the decimal point minutes
than desired. The toFixed method sets the number of places to display
after the decimal point. This is just one of many situations in which Video Reference:
numbers can be formatted. Domain 2
Topic: Primitive Data Types
Purpose: Subtopic: Format Numbers
After completing this project, you will be able to format numbers to
improve their look on a webpage. Objectives Covered:
2 Variables, Data Types, and
Functions
21 | Domain 2 2.1 Declare and
JavaScript use variables
Project Workbook
of primitive data types
1.j Formatting numbers
Steps for Completion:
1. Open the 21j-formatting-numbers.htm file from the Music2 Student folder in a web browser.
2. Click the Update Cart button. The sales tax and total amounts should be formatted to two decimal
places, not the number showing.
3. Open the 21j-formatting-numbers.htm file in your code editor.
4. Scroll down near the end of the file, specifically to this comment: <!-- the sales tax and the total need
to be converted to two decimal places -->
5. Inside the button code inside of the order_buttons div class, format the salesTax element to show two
numbers after the decimal point.
6. Format the grandtotal element to show two numbers after the decimal point.
7. Save your changes.
8. Preview the webpage in a web browser.
9. Click the Update Cart button. The sales tax and total should now display with two decimal places.

String Operations Project Details

There are many ways to manipulate strings. To concatenate strings is to Project Files:
combine pieces of strings together. Knowing the length of a string will 21k-practice-strings.htm
determine if it will fit a defined space in a document. String operations
can also include controlling how numbers display within a webpage. Estimated Completion
Time:
Another string operation to consider is that of nesting quotes. Single minutes
quotes can be nested within double quotes and vice versa. The key is
knowing which quotes you wish to display, if applicable. Those should be
the inner quotes within a set of nested quotes. Video Reference:
Domain 2
Topic: Primitive Data Types
Purpose: Subtopic: String Operations;
Upon completing this project, you will know how to find the length of a Nested Quotes
string and be able to concatenate strings. You will also know how to
control nested quotes.
Objectives Covered:
2 Variables, Data Types, and
Steps for Completion: Functions
1. Open the 21k-practice-strings.htm file from the Music2 folder in a 2.1 Declare and use variables
of primitive data types
web browser.
2.1.k 1.k String
2. Adjust msg2 to display as a number set to three digits. operations
3. Save your changes. 2.1.l Single quote vs.
double quote (nesting)
4. Preview the webpage in a web browser.
5. Enter 40 for the number of hours you can practice and select the Enter key.
6. Open the Console.
7. Use the Console to find the length of the practiceweeks paragraph string. What is the length of the
practiceweeks paragraph string?
8. Return to your code editor.
9. Change the quote structure in msg7 to have the phrase, dream?, in single quotes.
10. Save your changes.
11. Preview the webpage in a web browser.
12. Enter 40 for the number of hours you can practice and select the Enter key. The phrase, dream?,
should be in single quotes.

22 | Domain 2 JavaScript Project Workbook


Initialization Project Details

Initialization is storing or assigning a value in a variable. A declaration is Project Files:


the creation of a variable without it being initialized. A variable can be 21m-cart-variables.htm
initialized at any time.
Estimated Completion
Purpose: Time:
Upon completing this project, you will know the difference between minutes
declaration and initialization.
Video Reference:
Steps for Completion: Domain 2
1. Open the 21m-cart-variables.htm file from the Music2 Student Topic: Primitive Data Types
folder in a web browser. Subtopic: Initialization
2. In the Script section, which of the five declared variables have been
initialized? Objectives Covered:
2 Variables, Data Types, and
Functions
Which of the variables have been declared but not initialized? 2.1 Declare and use variables
3. of primitive data types
Initialization
4. Close all open files in both your web browser and your code editor.

Build and Iterate Through Project Details

Project Files:
Arrays 22a-tuningkits-array.htm

An array has multiple containers that contain multiple values. Where a


variable has one container with one value, an array will have multiple
Estimated Completion
containers, each storing an item. A single-dimensional array has one Time:
minutes
row of containers within its box and these containers will have a single
value in each. The single-dimensional array will show all the items in the
array on one line within one set of brackets. Similar to variables, arrays Video Reference:
can be declared and initialized at the same time or declared and then Domain 2
initialized later. Topic: Declare and Use Arrays
Subtopic: Build and Define
an Array; Iteration and
The array length is needed when iterating through an array. A loop is Length; Initialization
used to iterate through an array and will connect all the containers of
an array and allow easy repetition of an action while the conditions are
being met. This will allow you to change the style of a single- Objectives Covered:
dimensional array. 2 Variables, Data Types, and
Functions
2.2 Declare and use arrays
Purpose: 2.a Single-dimensional arrays
Upon completing this project, you will be able to understand and build 2.2.c Iteration
the code of a single-dimensional array. You will also be able to use a 2.2.d Initialization
loop to iterate through an array. 2.2.e 2.e Define, sort,
and search an array

Steps for Completion:


1. Open the 22a-tuningkits-array.htm file from the Music2 Student folder.
2. Scroll down to the comment, // declare array here.
3. Replace the comment with a single-dimensional array named tuningList 4. Within the tuningList
array, add the values, Tuning Lever and Tuning Fork
5. Save your changes.
6. Preview the webpage in a web browser.

23 | Domain 2 JavaScript Project Workbook


7. Click the Update List button. You should see the page update with the array values and a
message that says, A tuning lever and tuning fork is a must-have for any tuning kit
8. Return to the code editor.
9. Uncomment the lines containing the opening and closing ul tags for the tuningList HTML element.
10. Replace the text, // insert loop here, with a for loop that iterates through the elements in the tuningList
array, ensuring that each element appears as a bullet.
11. Save your changes.
12. Preview the webpage in a web browser.
13. Click the Update List button. The array values should now appear as a bulleted list.

Sorting and Searching Project Details

Sorting and searching an array will allow you to find content that should Project Files:
or should not be in the array. Sorting an array list will display the list in 22e-tuningkits-array.htm
alphabetical order. When searching for an array element, understand
that the first element in an array is element 0. Often, one will use the Estimated Completion
Console to search for an array element. If an element is in an array, it Time:
will return its position. If not, it will return a -1. minutes

Purpose: Video Reference:


Upon completing this project, you will be able to sort an array and Domain 2
search for content in an array. Topic: Declare and Use Arrays
Subtopic: Sorting and
Steps for Completion: Searching
1. Open the 22e-tuningkits-array.htm file from the Music2 Student
folder. Objectives Covered:
2. On the first line inside of the updateList function, add code to sort 2 Variables, Data Types, and
Functions
the tuningList array in alphabetical order.
2.2 Declare and use arrays
3. Save your changes. 2.e Define, sort, and search an
4. Preview the webpage in a web browser. array
5. Click the Update List button. In the bulleted list that appears, the tuning fork should appear before the
tuning lever.
6. Open the Console.
7. Search the array in the Console to find out if the Tuning Lever has a number.

8. Does Tuning Lever have a number in the array?


9. Search the array to find out if Felt Strips has a number.
Project Details
10. Does Felt Strips have a number in the array?

Push and Pop Project Files:


22f-tuningkits-array.htm

JavaScript has commands we can use to control what is in an array after


the array has been initialized. Push will add an item to an array, while Estimated Completion
pop will remove the last item in an array. Pop is best used in a last in, Time:
first out situation. minutes

Purpose: Video Reference:


Upon completing this project, you will be able to push an item into an Domain 2
array, and pop the last item out of the array. Topic: Declare and Use Arrays
Subtopic: Push and Pop
Steps for Completion:
1. Open the 22f-tuningkits-array.htm file from the Music2 Student Objectives Covered:
folder. 2 Variables, Data Types, and
Functions
2.2 Declare and use arrays
24 | Domain 2 JavaScript
2.f Push, pop,Project Workbook
shift, and
unshift
methods
2. Find the first article with the class, threecol1.
3. For the input check box with the ID of electronicTuner, add an onclick event with a function that will
push the item, Electronic tuner, to the tuningList array.
4. For the input check box with the ID of wedgeMute, add an onclick event with a function that will push
the item, Wedge mute to the tuningList array.
5. For the input check box with the ID of pappsMute, add an onclick event with a function that will push
the item, Papps mute, to the tuningList array.
6. For the input check box with the ID of feltStrips, add an onclick event with a function that will push the
item, Felt strips, to the tuningList array.
7. Save your changes.
8. Preview the webpage in a web browser.
9. Select the Wedge mute check box.
10. Click Update List. The tuning list should show three bulleted items.
11. Open the Console.
12. In the Console, pop a list item from the array. Which item was removed from the list?
13. Check that the Wedge mute item is no longer in the array.

Shift and Unshift Project Details

Shift will remove the first item in an array, while unshift will add an item Project Files:
to the beginning of an array. Shift is similar to pop as they both remove 22g-tuningkits-array.htm
items from an array, though pop removes an item from the end of an
array. Unshift is similar to push as both commands add to an array, Estimated Completion
though push adds an item to the end of an array. Time:
minutes
Purpose:
Upon completing this project, you will be able to know when to use the Video Reference:
Console or array code to add or remove items from an array. You will be Domain 2
able to use shift to remove items from an array and unshift to add items Topic: Declare and Use Arrays
to an array. Subtopic: Shift and Unshift

Steps for Completion: Objectives Covered:


1. Open the 22g-tuningkits-array.htm file from your Music2 Student 2 Variables, Data Types, and
folder in a browser. Functions
2. Open the Console. 2.2 Declare and use arrays
2.f Push, pop, shift, and
3. Shift a list item from the tuningList array. What list item was
unshift
removed from the array? methods

4. Open the 22g-tuningkits-array.htm file in your code editor.


5. Within each of the input check box tags for the threecol1 articles, change the onClick functions to run
from push to unshift.
6. Within the updateList function, comment out the tuningList.sort method.
7. Save your changes.
8. Preview the webpage in a web browser.
9. Select the Wedge mute check box.
10. Click the Update List button. Where did the unshift place Wedge mute in the tuningList array?

25 | Domain 2 JavaScript Project Workbook


Access an Element Project Details

The array index number is used to access an element in an array. The Project Files:
first item in an array is index number zero. After that, each item number 22h-tuningkits-array.htm
increments by one through the arrays.
Estimated Completion
Purpose: Time:
Upon completing this project, you will be able to access an array minutes
element using an index number.
Video Reference:
Steps for Completion: Domain 2
1. Open the 22h-tuningkits-array.htm file from the Music2 Student Topic: Declare and Use Arrays
folder. Subtopic: Access an Element;
Understanding Multi-
2. At the end of the updateList function, create an alert that says The Dimensional Arrays
first item in this array is and use the index number for the first
item in the array to access the element.
Objectives Covered:
3. Save your changes. 2 Variables, Data Types, and
4. Preview the webpage in a web browser. Functions
5. Select the Wedge mute check box. 2.2 Declare and use arrays
2.2.g 2.g
6. Click the Update List button. You should get an alert indicating that Length property
the first item in the array is the Wedge mute. 2.2.h 2.h
Access an array
Using Multi-Dimensional Projectelement
Details

Project Files:
Arrays 22j-tuningkits-array.htm

To this point, arrays we have seen have been single-dimensional arrays,


that is, array lists with one group of values. Arrays, however, can be Estimated Completion
multi-dimensional, as they can contain a group and then within each Time:
group, another group. Here is a real-life example: an array contains a minutes
list of locations, and within each location, amenities. The location and
the amenities would serve as the two dimensions. Video Reference:
Domain 2
Purpose: Topic: Declare and Use Arrays
Subtopic: Access an Element;
Upon completing this project, you will better understand and be able to
Understanding Multi-
use multidimensional arrays. Dimensional Arrays

Steps for Completion: Objectives Covered:


1. Open the 22j-tuningkits-array.htm file from the Music2 Student 2 Variables, Data Types, and
folder. Functions
2. Notice the multiArray function, which declares a two-dimensional 2.2 Declare and use arrays
array with two elements in each container. 2.b Multi-dimensional
arrays
3. Replace the comment, // set the 0,0 element of a1, with the code
that will set the 0,0 element of a1 to Tuning Fork and Red.
4. Save your changes.
5. Preview the webpage in a web browser. You should see the array at the bottom of the page.
6. Close all of your open files in both your browser and your code editor.

26 | Domain 2 JavaScript Project Workbook


Properties and Project Details

Project Files:
Methods 23a-cart-constants.htm

A property is a characteristic of an object and a method is an action


toward an object or property. A method will always have parentheses at
Estimated Completion
the end to specify what is being taken action on. Time:
minutes

Purpose:
Upon completing this project, you will be able to recognize both Video Reference:
Domain 2
properties and methods and write code using methods.
Topic: Complete and Debug
Code on
Steps for Completion: Objects
1. For each expression, identify whether the expression is a property or Subtopic: Properties; Methods
method:
a. innerHTML: Objectives Covered:
2 Variables, Data Types, and
b. document.getElementById: Functions
2.3 Complete and debug code
c. push: that uses objects
d. length: 2.3.a 3.a Properties
2.3.b 3.b Methods
2. Open the 23a-cart-constants.htm file from the Music2 Student
folder.
3. Find the comment, // set the discount to two decimal points.
4. On the line below the comment, add a method to the discount result that will set the result to be fixed
to two decimal points.
5. Save your changes.
6. Preview the webpage in a web browser. The dollar amounts at the bottom of the page should be set to
two decimal points.

Instantiation Project Details


Instantiation is the creation of a new template or class for an object. Project Files:
When a class is used to define an object, it creates consistency among 23c-products-class.htm
objects and the manner in which they are created. For this reason, 23c-main.js
classes are often created in an external JavaScript file, so that multiple
files can access the class.
Estimated Completion
Time:
Purpose: 10-15 minutes
Upon completing this project, you will be able to instantiate a class in
JavaScript to create consistency.
Video Reference:
Domain 2
Steps for Completion: Topic: Complete and Debug
1. Open the 23c-main.js file from the Music2 Student scripts folder. Code on
2. Replace the comment, // insert product class here, with a class for a Objects
new product that will contain three objects: item, size, and price. Subtopic: Instantiation

3. Save your changes.


4. Open the 23c-products-class.htm file from the Music2 Student Objectives Covered:
2 Variables, Data Types, and
folder.
Functions
5. Below the footer, add an opening and closing script tag. 2.3 Complete and debug code
6. Within the script tag, add a new instance of the product class named that uses objects
mandolin with the following details: Instantiation

27 | Domain 2 JavaScript Project Workbook


a. item: Mandolin
b. size: 36”
c. price: 379.99
7. Within the script tag, add a new instance of the product class named drum with the following details:
a. item: Drum
b. size: 32”
c. price: 129.99
8. Save your changes.
9. Preview the webpage in a web browser.
10. Open the Console.
11. Return the size of the mandolin. It should be 36”.
12. Return the price of the drum. It should be 129.99.

Date Object and Time Project Details

The date and time object can be used to build a date variable and Project Files:
retrieve date parts using mathematics and built-in JavaScript methods. 23d-practice-dates.htm

Purpose: Estimated Completion


Upon completing this project, you will be able to build date variables Time:
and retrieve date parts. minutes

Steps for Completion: Video Reference:


1. Open the 23d-practice-dates.htm file from the Music2 Student Domain 2
folder. Topic: Complete and Debug
Code on
2. Just below the opening script tag, declare a date variable named Objects
lessonStartDate with a fixed date and time of October 2, 2018 at Subtopic: Date Object and
6:00 PM. Time
3. On the next line, declare a date variable named today with the
current date. Objectives Covered:
4. Save your changes. 2 Variables, Data Types, and
Functions
5. Preview the webpage in a web browser.
2.3 Complete and debug code
6. Open a Console window. that uses objects
7. Display the lessonStartDate variable. It should show a date of Date object
Project Details
October 2, 2018.
8. Display the today variable. It should show the current date. Project Files:
23e-practice-dates.htm
Retrieving Date Parts
JavaScript will return most date parts as numbers (including for months, Estimated Completion
which are numbered 0 through 11). This complicates returning a month Time:
name. The month, day, and year of a date must be retrieved minutes
individually, using the getMonth, getDay, and getFullYear methods,
respectively. To return the month name you will need to build an array Video Reference:
with all the month names and tie the array to the month number. Domain 2
Topic: Complete and Debug
Code on
Purpose:
Objects
Upon completing this project, you will be able to retrieve date parts and Subtopic: Retrieving Date
have the month name returned as the month value. Parts

Steps for Completion: Objectives Covered:


1. Open the 23e-practice-dates.htm file from the Music2 Student 2 Variables, Data Types, and
folder. Functions
2.3 Complete and
28 | Domain 2 JavaScript
debug Project
code that uses Workbook
objects
3.e Retrieve date and time
parts
2. Replace the comment, // get the month of the lesson, with the month of the
lessonStartDate variable.
3. Save your changes.
4. Preview the webpage in a web browser.
5. Click in the Enter the number of hours field.
6. Type: 20 and press the Enter key. Notice the message that displays that classes start in and then a
month number.
7. Return to your code editor.
8. Replace the comment, // declare month array here, with a variable named monthArray that has an
array of all 12 months of the year.
9. On the line where you obtained the month of the lessonStartDate variable, change the method to get
the month name from the monthName array.
10. Save your changes.
11. Preview the webpage in a web browser.
12. Click in the Enter the number of hours field.
13. Type: 20 and press the Enter key. Notice the message that displays that classes start in and then a
month instead of a month number.

Localization Project Details

Date localization uses the toLocaleDateString method to have the date Project Files:
display in a localized format. As an example, location date formats are 23f-practice-dates.htm
mm/dd/yyyy for the USA and dd/mm/yyyy for the UK.
Estimated Completion
Purpose: Time:
Upon completing this project, you will be able to localize dates using 10-15 minutes
JavaScript.
Video Reference:
Steps for Completion: Domain 2
1. Open the 23f-practice-dates.htm file from the Music2 Student Topic: Complete and Debug
Code on
folder.
Objects
2. Replace the comment, // insert localized date, with a reference to Subtopic: Localization
the lessonStartDate variable, formatted in the UK format.
3. Save your changes.
Objectives Covered:
4. Preview the webpage in a web browser. 2 Variables, Data Types, and
Project Details
Functions
5. Click in the Enter the number of hours field.
2.3 Complete and debug code
6. Type: 20 and press the Enter key. Notice that the start date is in the Project Files:
that uses objects
UK format of dd/mm/yyyy. 23g-practice-dates.htm
3.f Localize date format (MM/
7. Return to your code editor. DD vs DD/MM)
8. Change the locale of the start date to display in mm/dd/yyyy format. Estimated Completion
9. Save your changes. Time:
10. Preview the webpage in a web browser. minutes
11. Click in the Enter the number of hours field.
12. Type: 20 and press the Enter key. Notice that the start date is in the Video Reference:
US format of mm/dd/yyyy. Domain 2
Topic: Complete and Debug

Add and Subtract Dates Code on


Objects
Adding and subtracting dates in JavaScript use different default Subtopic: Add and Subtract
Dates
intervals. When a number is added to a date, JavaScript assumes the
number to be the number of days to add. When two dates are
subtracted in JavaScript, the return will be in milliseconds. The code will Objectives Covered:
2 Variables, Data Types, and
Functions
29 | Domain 2 JavaScript
2.3 Project
Complete and Workbook
debug code
that uses objects
3.g Add and subtract dates
need to be written so that 86400000 milliseconds in a day will be divided into the returned
milliseconds from the subtraction to return the number of days.

Purpose:
Upon completing this project, you will be able to add and subtract dates using JavaScript.

Steps for Completion:


1. Open the 23g-practice-dates.htm file from the Music2 Student folder.
2. Replace the comment, // declare lessonEndDate here with a variable named lessonEndDate that is set
to the lessonStartDate.
3. On the next line, set the lessonEndDate to be 56 days after the lessonStartDate.
4. Save your changes.
5. Preview the webpage in a web browser.
6. Click in the Enter the number of hours field.
7. Type: 20 and press the Enter key. Notice the end date of 11/27/2018.
8. Open a Console.
9. Calculate the difference between the lessonEndDate and the lessonStartDate. What is the difference in
milliseconds? .
10. Change the calculation so that the result is returned in weeks. You should see 8 weeks as a result.
11. Close your open files, both in the browser and in your code editor.

Random Numbers Project Details

A random number generator can be used when creating an online quiz Project Files:
or game with JavaScript. The Math.random method will return the 24a-jukebox.htm
numbers 0 or 1. The number returned should then be multiplied by the Blues.mp4
number of random choices needed for the project and set to use the Happy.mp4
Math.floor function if you want the lowest possible integer returned (0
and 1 for two numbers, for example). Estimated Completion
Time:
Purpose: 5-10 minutes
Upon completing this project, you will be able to use the Math.random
method to allow JavaScript to choose randomly between two videos to Video Reference:
display upon webpage loading. Domain 2
Topic: Built-In Math Functions
Steps for Completion: Subtopic: Random
1. Open the 24a-jukebox.htm file from the Music2 Student folder.
2. Between the opening and closing script tags at the bottom of the Objectives Covered:
page, add a function named loadJukebox 2 Variables, Data Types, and
Functions
3. Within the loadJukebox function, add a variable named
2.4 Complete and debug code
videoNumber that is set to generate a random number of either 0 that uses built-in Math
or 1. functions
4. Add an if else statement that satisfies the following conditions: 4.a Random
a. If the videoNumber is 0, set the source of the HTML element videoJukebox to the Blues.mp4 video
in the Videos folder.
b. If the videoNumber is 1, set the source of the HTML element videoJukebox to the Happy.mp4 video
in the Videos folder.
5. Save your changes.
6. Preview the webpage in a web browser.
7. Refresh the webpage a few times. Sometimes a happy song will be ready to play and sometimes a
blues song will be ready to play.

30 | Domain 2 JavaScript Project Workbook


Rounding and Absolute Project Details

Project Files:
Methods 24b-practice-numbers.htm

The round method will round a number to the nearest whole number.
The Math.round method in JavaScript is used to round numbers. The
Estimated Completion
absolute value of a number, represented by the Math.abs method, is Time:
5-10 minutes
the absolute distance of a number from zero. For example, -3 and 3
both have an absolute value of 3.
Video Reference:
Purpose: Domain 2
Topic: Built-In Math Functions
Upon completing this project, you will be able to write code using the
Subtopic: Round; Abs
Math.round method to round a number to the nearest whole number
using JavaScript. You will also be able to use the Math.abs method to
get the absolute value of a number. Objectives Covered:
2 Variables, Data Types, and
Functions
Steps for Completion: 2.4 Complete and debug code
1. Open the 24b-practice-numbers.htm file from the Music2 Student that uses built-in Math
folder. functions
2. Within the getPracticeHours function, round the result for the msg2 2.4.b 4.b Round
variable to the nearest whole number. 2.4.c Abs

3. Within the getPracticeHours function, make the hoursEntered variable calculation an absolute value.
4. Save your changes.
5. Preview the webpage in a web browser.
6. Click in the Enter the number of hours field.
7. Type: -20 and press the Enter key. You should see the result round up to one week and the number one
should be a positive integer since the Math.abs method was used.

Floor and Ceiling Project Details

The floor and ceiling method will not take into consideration what is Project Files:
after the decimal point in a number when displaying the number as an 24d-practice-numbers.htm
integer. To return the nearest lower whole number, use the Math.floor
method. To return the nearest higher whole number, use the Math.ceil Estimated Completion
method. At times, the floor or ceiling method can return a more precise Time:
whole number than the round method. When calculating days or time, minutes
the highest whole number is often needed, thus making it necessary to
use the Math.ceil method.
Video Reference:
Domain 2
Purpose: Topic: Built-In Math Functions
Upon completing this project, you will be able to determine which Subtopic: Floor and Ceiling
method is best to use between the Math.floor and Math.ceil methods to
get a more precise whole number return.
Objectives Covered:
2 Variables, Data Types, and
Steps for Completion: Functions
1. Open the 24d-practice-numbers.htm file from the Music2 folder 2.4 Complete and debug code
in a web browser. that uses built-in Math
functions
2. Click in the Enter the number of hours field. 2.4.d Floor
3. Type: 6 and press the Enter key. Notice that the results show 3 hours 2.4.e 4.e Ceil a
week of practice, which, multiplied by 6 weeks, falls short of the
total of 20 hours.
4. Open the 24d-practice-numbers.htm file in your code editor.

31 | Domain 2 JavaScript Project Workbook


5. For the msg2 variable, replace the Math.round method with a method that will always
move the variable up to the next integer.
6. Save your changes.
7. Preview the webpage in a web browser.
8. Click in the Enter the number of hours field.
9. Type: 6 and press the Enter key. Notice that the results now show 4 hours a week of practice, which,
multiplied by 6 weeks, exceeds the total of 20 hours.
10. Open a Console.
11. Type: Math.floor (20/6) and press the Enter key. What is the result?

Min and Max Project Details


Min and max will retrieve the minimum or maximum number in a range Project Files:
of numbers, respectively. Variables are usually used to create the range 24f-cart-max-min.htm
to pull the data from using the Math.min or Math.max method.

Estimated Completion
Purpose:
Upon completing this project, you will be able to create variables that
Time:
minutes
will return the min and max prices from a list of prices.

Steps for Completion: Video Reference:


Domain 2
1. Open the 24f-cart-max-min.htm file from the Music2 Student Topic: Built-In Math Functions
folder. Subtopic: Min and Max
2. Near the end of the webpage, replace the comment starting with the
phrase, get the mininum, with a method that will get the lowest
price among these three variables: manprice, drumprice, and Objectives Covered:
tromprice. 2 Variables, Data Types, and
Functions
3. Replace the comment starting with the phrase, get the maximum, 2.4 Complete and debug code
with a method that will get the highest price among these three that uses built-in Math
variables: manprice, drumprice, and tromprice. functions
2.4.f 4.f Min
4. Save your changes.
2.4.g 4.g Max
5. Preview the webpage in a web browser.
6. Click the Update Cart button. You should see the lowest and highest priced items.

Powers and Square Roots Project Details

The Math.pow method will take a number and raise it according to the Project Files:
power number specified. When a number is raised to the power of a 24g-square-footage.htm
number, it takes the number multiplied by the same number as many
times as the power specifies. Estimated Completion
Time:
The Math.sqrt method will take a number and calculate the square root minutes
of the number. As an example, this is used to determine the length of a
side if the square footage is known. Video Reference:
Domain 2
Purpose: Topic: Built-In Math Functions
Upon completing this project, you will be able to write JavaScript code Subtopic: Pow; Sqrt
that will use the Math.pow method to find the square footage for the
user of a webpage. You will also be able to use the Math.sqrt method to Objectives Covered:
calculate and return the square root from the input of the square 2 Variables, Data Types, and
footage. Functions
2.4 Complete and debug code
that uses built-in Math
functions
Steps for Completion: 2.4.h 4.h Pow
2.4.iSqrt
32 | Domain 2 JavaScript Project Workbook
1. Open the 24g-square-footage.htm file from the Music2 folder.
2. In the getSquareFootage function, replace the comment, // add power method, with the method use to
raise the integer being parsed to the second power.
3. Replace the comment, // add square root method, with the method used to obtain the square root of
the integer being parsed.
4. Save your changes.
5. Preview the webpage in a web browser.
6. Enter the number 441 in the last text box on the webpage.

7. Click the Square Footage button. What is the result?

8. Click the Side button. What is the result?


9. Close all of your open files in both your browser and your code editor.

Reusable Code Project Details

Functions are created so there is reusable code that can be used in Project Files:
multiple areas. If changes need to be made to code, with a function, the 25a-cart-numbers.htm
code will only need to be changed in one place instead of multiple
places. When code is reused it also lessens the amount of code to write Estimated Completion
and organizes the code. Time:
5-10 minutes
Purpose:
Upon completing this project, you will be able to create functions that Video Reference:
allow you to reuse code and organize the code. Domain 2
Topic: Parameters and Return
Steps for Completion: Values
Subtopic: Reusable Code
1. Open the 25a-cart-numbers.htm file from the Music2 Student
folder.
2. Replace the comment, // add addOne function, with a function Objectives Covered:
named addOne that will do the following: 2 Variables, Data Types, and
Functions
a. Store the existing quantity of a field in a variable named qty. Project Details
2.5 Complete and debug
b. Use a variable named newQty to parse, from the HTML element functions that accept
with the qty field, the value into an integer. Project Files:
parameters and return values
c. Increment the newQty variable by one. 5.a Reusable code
25b-cart-scopes.htm
d. Assign the newQty value to the HTML element with the qty field. 25b-main.js

3. Find the comment, // add reference to addOne function using


manqty. Estimated Completion
4. Replace the comment with a call to the addOne function using the Time:
manqty element. 5-10 minutes

5. Save your changes.


6. Preview the webpage in a web browser. Video Reference:
Domain 2
7. Click the + button on the mandolin item. The quantity should Topic: Parameters and Return
increase by one. Values

Scopes and Variable Defi


Subtopic: Local vs. Global
Scope;
Redefining Variables; Passing
A scope describes the depth, or availability of use, that a variable can Parameters
be used in a file. There are two factors that determine the scope: where
the variable is declared, and if it is specifically being declared by using Objectives Covered:
the var keyword. Local variables are only available within their function 2 Variables, Data Types, and
and have a local scope. Global variables are available anytime and have Functions a
global scope. A variable declared outside of functions or that does not 2.5 Complete and debug
use the var keyword has a global scope. functions that accept
parameters and return values
2.5.b 5.b Local vs. global
33 | Domain 2 scope Project Workbook
JavaScript
2.5.c Redefine variables
2.5.d Pass parameters
Purpose:
Upon completing this project, you will know the difference between local and global variables and where
they are available to use. You will also be able to identify parameters within functions.

Steps for Completion:


1. Open the 25b-cart-scopes.htm file from the Music2 Student folder.
2. Open the 25b-main.js file from the Music2 Student scripts folder.

3. In the main.js file, is the incMsg variable local or global?

4. Which variable cannot be redefined?


5. Switch to the 25b-cart-scopes.htm file.
6. Scroll down to the script section near the end of the document. Which variables are redefined within
their functions?

7. Is the qty variable a local or global variable?


8. Within the script, which functions are using parameters?

Value vs. Reference Project Details

Primitive data types can be easily set to be equal to another primitive Project Files:
data type, while objects cannot be changed in this way. An object 25e-cart-numbers.htm
references shared data space, so every object sharing the space will
change. Primitive data types will return a value that passes method Estimated Completion
arguments and creates a return. Object variables are referenced to a Time:
shared space and do not pass method arguments. With objects, it is minutes
best practice to set each object with its own value.

Video Reference:
Purpose: Domain 2
Upon completing this project, you will know the difference between a Topic: Parameters and Return
value and a reference. Values
Subtopic: Value vs. Reference
Steps for Completion:
1. Open the 25e-cart-numbers.htm file from the Music2 Student Objectives Covered:
folder in a web browser. 2 Variables, Data Types, and
Functions
2. Open the Console.
2.5 Complete and debug
3. In the Console, declare a variable of x and set it to 4 functions that accept
4. Declare a variable of y and set it to x. parameters and return values
5.e Value vs. reference
5. Set y to be equal to 7
6. What is the value of x after y has been made equal to 7?

7. If x and y were an array, would the value of x stay the same?

8. Why will the object value change when it is set equal to another object?

9. Can an object have a set value?


10. What needs to be done for an object to have a set value?

34 | Domain 2 JavaScript Project Workbook


Return Values Project Details

A return value is an answer to a function calculation. The return Project Files:


keyword is used to return a function result that is then used in another 25f-practice-numbers.htm
process, such as assigning the result to an HTML element, for example.
Estimated Completion
Purpose: Time:
Upon completing this project, you will be able to use a return keyword minutes
as part of a function.
Video Reference:
Steps for Completion: Domain 2
1. Open the 25f-practice-numbers.htm file from the Music2 Student Topic: Parameters and Return
Values
folder.
Subtopic: Return Values
2. In the lessonSchedule function near the bottom of the page, create a
return statement that will return the month by name (Hint: look for
code to help generate a month name). Objectives Covered:
2 Variables, Data Types, and
3. In the body tag, set the lessonSchedule function to run when the Functions
webpage loads. 2.5 Complete and debug
4. Save your changes. functions that accept
parameters and return values
5. Preview the webpage in a web browser. You should see an alert with
5.f Return values
the current month.
6. Close all of your open files in your code editor and your browser.

35 | Domain 2 JavaScript Project Workbook


Fill-in-the-Blanks Domain 3
Instructions: While watching Domain 3, fill in the missing words according to the information presented by
the instructor.
[References are found in the brackets.]

Logical and Comparison Operators

1. Evaluation expressions compare two parts, usually an and a , and


return a true or false value. [Equals]

2. In JavaScript, the symbol representing that something is not equal to a value is the symbol. [Not
Equals]

3. The less than and greater than symbols in JavaScript are the same as they are for basic
elements. [Greater Than and Less Than]

4. A common logical problem in JavaScript is not to have the proper for a less than or less than or
equal to situation. [Less Than or Equal To]

5. With greater than and greater than or equal to, you must figure out if the requires the number
in question to be included. [Greater Than or Equal To]

15. A do loop runs and then checks the condition. [Do]

16. Sometimes within a , we need to break code. [Break]

one iteration of the loop based on a condition.


17. The continue keyword [Continue]
6. We saw that the != means not equal to, the ! part is the part and it can be used other places
besides before an =. [Not]

7. The and symbol is two . [And]

8. An or operator is a symbol. [Or]

Decision Statements

9. In JavaScript, the condition for an if statement is always inside . [If]

10. When using the if keyword to see if a situation is true, you may want to check for another situation
in case the first situation is . [Else If]

11. Unlike an statement, a switch statement will not stop checking a condition after a first match.
[Switch]

12. A nested if statement is an statement inside of an if statement. [Nested If]

Loops

13. The for loop runs a set number of times, either set by us or set by a . [For]

37 | Domain 3 JavaScript Project Workbook


14. The while loop is defined as this: while this condition is run this code. [While]

Equals and Not Equals Project Details


The equal sign will set the variable equal to a value, while the double Project Files:
equal sign asks the following question: is the variable equal to a set 31a-cart-evaluation.htm
value? The double equal is normally used in a statement such as an if
statement, which is covered later in this domain. The sign used in
JavaScript to represent a not equal is an exclamation point in front of an Estimated Completion
equal sign (!=). Time:
minutes

Purpose:
Upon completing this project, you will be able to determine when to use Video Reference:
the equal sign, the double equal sign, and the not equal sign. Domain 3
Topic: Logical and Comparison
Operators
Steps for Completion: Subtopic: Equals; Not Equals
1. Open the 31a-cart-evaluation.htm file from the Music3 Student
folder.
Objectives Covered:
2. In the script section near the bottom of the page, replace the 3 Decisions and Loops
comment, // add set operator, with the correct operator to set the
3.1 Evaluate expressions that
checkOutExists variable to false. use logical and comparison
3. Replace the comment, // add conditional operator, with the correct operators
operator to see if the checkOutExists variable is false. 1.a !=
1.g ==
4. Replace the comment, // add not equal operator, with the correct
operator to see if the checkOutExists variable is not false.
5. Save your changes.
6. Preview the webpage in a web browser.
7. Click the Checkout button. A checkout window should appear.
8. Click the Close Checkout button. The checkout window should close.

Greater Than or Less Than Project Details

Greater than and less than comparison operators are normally used in Project Files:
conditional statements. A conditional statement is an if statement that 31c-practice-comparison.htm
returns a true or false.
Estimated Completion
Purpose: Time:
Upon completing this project, you will be able to create a greater than minutes
statement and a less than statement that will return a specific message
when a condition is met. Video Reference:
Domain 3
Steps for Completion: Topic: Logical and Comparison
1. Open the 31c-practice-comparison.htm file from the Music3 Operators
Subtopic: Greater Than and
Student folder.
Less Than
2. Replace the comment, // are less than 3, with the correct operator to
test if the hoursEntered are less than 3 hours.
Objectives Covered:
3. Replace the comment, // are more than 8, with the correct operator 3 Decisions and Loops
to test if the hoursEntered are more than 8 hours.
3.1 Evaluate expressions that
4. Save your changes. use logical and comparison
5. Preview the webpage in a web browser. operators
3.1.b 1.b <
3.1.c>

38 | Domain 3 JavaScript Project Workbook


6. Click in the Enter number of hours field.
7. Type: 2 and press the Enter key. You should see a message suggesting practicing at least three hours a
week.
8. Type: 10 and press the Enter key. You should see a message suggesting that may be too much practice
for a beginner.

Other Comparison Project Details

Operators Project Files:


31d-practice-comparison.htm
The less than or equal to is a logical operator that will allow a number
and anything less than the number to return a value. The greater than Estimated Completion
or equal to is a logical operator that will allow the number and anything Time:
greater than the number to be included in the returned value. It is minutes
important to understand the logic behind what you are creating to know
when to use less than or equal to or just the less than sign as well as
the greater than or equal to or greater than sign. You also want to make Video Reference:
Domain 3
sure any messages to users convey your logic properly.
Topic: Logical and Comparison
Operators
Purpose: Subtopic: Less Than or Equal
Upon completing this project, you will be able to use the less than or To;
equal to sign and greater than or equal to sign to return a specific Greater Than or Equal To
message when the operating conditions are met.
Objectives Covered:
Steps for Completion: 3 Decisions and Loops
1. Open the 31d-practice-comparison.htm file from the Music3 3.1 Evaluate expressions that
Student folder. use logical and comparison
operators
2. Find the hoursEntered < 3 condition and change it to include the 3.1.d <=
number 3. 3.1.e 1.e >=
3. Change the accompanying message for the condition to indicate
that more than three hours of practice are needed.
4. Find the hoursEntered > 8 condition and change it to include the number 8.
5. Change the accompanying message for the condition to indicate that eight or more hours of practice
may be too much.
6. Save your changes.
7. Preview the webpage in a web browser.
8. Click in the Enter the number of hours field. Project Details
9. Type: 3 and press the Enter key. You should see a message
suggesting practicing more than three hours a week. Project Files:
10. Type: 8 and press the Enter key. You should see a message 31f-cart-evaluation.htm
suggesting that may be too much practice for a beginner.

Not Estimated Completion


Time:
An exclamation point is the sign for not and can be used in many 5-10 minutes
places. The not sign is especially valuable when evaluating Boolean
situations. Boolean variables can use the not sign and require less Video Reference:
written code. The not sign is most often used to see if a Boolean Domain 3
variable is false. Topic: Logical and Comparison
Operators
Subtopic: Not

Objectives Covered:
3 Decisions and Loops
3.1 Evaluate expressions that
39 | Domain 3 JavaScript
use logical andProject Workbook
comparison
operators
1.f !
Purpose:
Upon completing this project, you will be able to use a not sign to shorten the code in a Boolean situation.

Steps for Completion:


1. Open the 31f-cart-evaluation.htm file from the Music3 Student folder.
2. Find the openCheckOut function near the bottom of the page.
3. Replace the code, checkOutExists == false, with code that uses the not operator to test to see if the
checkOutExists variable is indeed false.
4. Save your changes.
5. Preview the webpage in a web browser.
6. Click the Checkout button. The checkout window should open.
7. Click the Close Checkout button. The checkout window should close.

And vs. Or Project Details


The and operator evaluates multiple expressions at the same time. The Project Files:
and symbol is && when used in JavaScript code. Both conditions need 31g-tuningkits-andor.htm
to be true for the and evaluator to return true.

Estimated Completion
The or evaluator needs only one of the expressions being evaluated to
be true to act. The or symbol is || when used in JavaScript code. This Time:
minutes
symbol is created by holding the Shift key and pressing the Backslash
key twice.
Video Reference:
Domain 3
Purpose:
Topic: Logical and Comparison
Upon completing this project, you will be able determine the two Operators
expressions that need to return true for an and evaluator to return a set Subtopic: And; Or
message.

Objectives Covered:
Steps for Completion: 3 Decisions and Loops
1. Open the 31g-tuningkits-andor.htm file from the Music3 Student
3.1 Evaluate expressions that
folder. use logical and comparison
2. Within the updateList function, replace the comment, // and, with operators
the and operator. 3.1.h 1.h &&
3. Replace the comment, // or, with the or operator. 3.1.i||
4. Save your changes.
5. Preview the webpage in a web browser.
6. Select both the Wedge mute and Papps mute check boxes. Project Details
7. Click the Update List button. You should see a message stating that
both mutes are selected. Project Files:
8. Clear the Wedge mute check box. 32a-cart-evaluation.htm

9. Click the Update List button. You should see a message stating that
one mute is selected. Estimated Completion
Time:
If-Else minutes

In programming, there are many situations in which a condition needs


to be checked and valued at either being true or being false. As is the
Video Reference:
Domain 3
case with many other programming languages, JavaScript uses an if
Topic: Decision Statements
Subtopic: If

Objectives Covered:
3 Decisions and Loops
40 | Domain 3 JavaScript
3.2 Project
Complete and debugWorkbook
decision statements
2.a Single alternative (if)
statement to check a condition. One or more actions can be taken if a condition is true. If a condition is
false, an else statement is then used to take one or more different actions.

Purpose:
Upon completing this project, you will know how to create an if statement and how the if statement
functions.

Steps for Completion:


1. Open the 32a-cart-evaluation.htm file from the Music3 Student folder.
2. Scroll down and find the openCheckOut function.
3. Replace the comment, // add the conditional keyword, with the keyword needed to check to see if the
condition is true.
4. Below the comment on consolidating the two functions, rework the closeCheckOut function so that it
does the following:
a. Becomes part of the openCheckOut function.
b. Becomes the action that runs if the condition checked in the openCheckOut
function is not true.
5. Remove any curly brackets and other punctuation no longer needed.
6. Rename the openCheckOut function to the word, checkOut
7. Save your changes.
8. Preview the webpage in a web browser.
9. Click the Checkout button. The checkout window should open.
10. Click the Close Checkout button. The checkout window should close.

Else If Project Details


In the previous project, you built an if-else statement, which checked a Project Files:
single condition and performed an action if it was true and a different 32b-tuningkits-andor.htm
action if it was false. Sometimes, more than one condition needs to be
checked. An else if statement can be used to check if a condition is true
after a previous condition has been established as false. You can have Estimated Completion
many else if portions within an overall if statement. Time:
minutes

With any form of an if statement, the code leaves the if statement as


soon as a condition returns true, no matter how many else if Video Reference:
statements exist within the if-else block. Domain 3
Topic: Decision Statements
Subtopic: Else If
Purpose:
Upon completing this project, you will be able to use an else if function
to add another action to an overall if statement. Objectives Covered:
3 Decisions and Loops

Steps for Completion: 3.2 Complete and debug


decision statements
1. Open the 32b-tuningkits-andor.htm file from the Music3 Student
2.b Dual alternative (if else)
folder.
2. Within the updateList function, replace the comment, // check this condition if the first one is false,
with the key phrase that will check this condition if the previous condition is false.
3. Repalce the comment, // do this if both conditions are false, with the keyword used to take action if
both conditions above are false.
4. Save your changes.

41 | Domain 3 JavaScript Project Workbook


5. Preview the webpage in a web browser.
6. Select the Wedge mute and Papps mute check boxes.
7. Click the Update List button. You should see a message indicating that both mutes are checked.
8. Clear the Wedge mute check box.
9. Click the Update List button. You should see a message indicating the one mute is checked.
10. Clear the Papps mute check box.
11. Click the Update List button. The message should disappear.

Switch Project Details


The switch keyword is used when multiple conditions need different Project Files:
actions taken. Each condition within a switch statement is represented 32c-cart-switch.htm
with the case keyword. The equivalent of an else keyword within a
switch statement is the default keyword. Unlike the if statement,
JavaScript needs to be told to exit the switch statement if the case Estimated Completion
condition is met. For this reason, after every case, a break statement Time:
needs to be made so that the block is exited from after a condition is minutes
met.
Video Reference:
Purpose: Domain 3
Upon completing this project, you will be able to create a switch Topic: Decision Statements
statement with multiple conditions to be tested. Subtopic: Switch

Steps for Completion: Objectives Covered:


1. Open the 32c-cart-switch.htm file from the Music3 Student folder. 3 Decisions and Loops

2. Find the showSpecialDiscount function. 3.2 Complete and debug


decision statements
3. Within the showSpecialDiscount function, replace the //check Multiple alternative (switch)
comment with the keyword used to start the statement that checks
for multiple conditions.
4. Replace each //when comment with the keyword used for a condition within the statement you created
in the previous step.
5. Replace each //exit comment with the keyword used to exit the statement.
6. Replace the //else comment with the keyword used for all other conditions within the statement.
7. Save your changes.
8. Preview your webpage in a web browser.
9. Click the Update cart button. If the current date is the 1st, 7th, or 15th of the month, you will see a
special message. Otherwise, you will see a message to keep
checking back for specials. Project Details

Nested If Project Files:


32d-tuningkits-andor.htm
A nested if statement is an if statement inside of an if statement. The
nested if statement is normally used when checking for one or more
conditions inside a condition that is found to be true. Estimated Completion
Time:
Purpose: 10-15 minutes
Upon completing this project, you will be able to nest an if statement
that will return different messages when set conditions are met. Video Reference:
Domain 3
Topic: Decision Statements
Subtopic: Nested If

Objectives Covered:
3 Decisions and Loops

42 | Domain 3 3.2 Complete and


JavaScript debug
Project Workbook
decision statements
Nested If
Steps for Completion:
1. Open the 32d-tuningkits-andor.htm file from the Music3 Student folder.
2. Find the updateList function.
3. Within the updateList function, add an if statement at the point of the comment that begins with, //
nest an if statement, that will do the following:
a. If the Wedge mute check box is selected, return the message indicating as such.
b. If the Papps mute check box is selected, return the message indicating as such.
4. Remember to add all appropriate punctuation.
5. Save your changes.
6. Preview the webpage in a web browser.
7. Select the Wedge mute check box.
8. Click the Update List button. You should see a message indicating that the Wedge mute check box is
selected.
9. Clear the Wedge mute check box.
10. Select the Papps mute check box.
11. Click the Update List button. You should see a message indicating that the Papps mute check box is
selected.
12. Close all of your open files, both in the browser and in your code
editor. Project Details

For Project Files:


33a-tuningkits-loops.htm
The for loop runs a block of code a set number of times. The run times
can be set by us or by a value. The for loop has three arguments: a
starting point, the loop stop point, and the number to increase or Estimated Completion
decrease each time the loop is run. Time:
5-10 minutes
Purpose:
Upon completing this project, you will be able to create and use a for Video Reference:
loop to run a block of code a set number of times. Domain 3
Topic: Loops
Steps for Completion: Subtopic: For

1. Open the 33a-tuningkits-loops.htm file from the Music3 Student


folder. Objectives Covered:
2. Find the updateList function. 3 Decisions and Loops

3. Within the updateList function, replace the comment, // start the for 3.3 Complete and debug loops
3.3.a 3.a For
loop, with the opening statement in a for loop to run through the
3.3.b 3.b For in
array of the tuningList variable. The loop should have the following:
a. A variable named i that starts at 0.
b. The length of the loop should be the length of the tuningList array.
c. The loop should increment by one each time the loop runs.
4. Save your changes.
5. Preview the webpage in a web browser..
6. Select the Papps mute check box.
7. Click the Update List button. The two tuning items and the Papps mute item should display as a
bulleted list.

43 | Domain 3 JavaScript Project Workbook


Do and While Loops Project Details
While the for loop runs a set number of times, do and while loops run Project Files:
based on a condition, specifically until a condition is met. The difference 33b-practice-loops.htm
between the two loops is simple: a while loop is not guaranteed to run
as it will not run when a condition has already been met. A do loop will
run at least once. Estimated Completion
Time:
10-15 minutes
When using a while loop, it is imperative to make sure a condition is
eventually met. Otherwise, you will have code that is stuck in an
endless loop. Video Reference:
Domain 3
Topic: Loops
Purpose:
Subtopic: While; Do
Upon completing this project, you will be able to create a while loop, a
do loop, and you will understand the difference between the two.
Objectives Covered:
3 Decisions and Loops
Steps for Completion:
1. Open the 33b-practice-loops.htm file from the Music3 Student 3.3 Complete and debug loops
folder. 3.3.c While
3.3.d Do while
2. Within the lessonSchedule function, replace the comment, // add
condition here, with a conditional loop to run so long as the lessonStartDate is less than the
lessonEndDate.
3. Save your changes.
4. Preview the webpage in a web browser.
5. Click in the Enter the number of hours per week field.
6. Type: 4 and press the Enter key. You should see a list of lesson dates.
7. Return to the code editor.
8. Adjust the syntax of the loop so that it runs at least once.
9. Save your changes.
10. Refresh the webpage in the web browser.
11. Click in the Enter the number of hours per week field.
12. Type: 4 and press the Enter key. You should still see a list of lesson dates.

Break and Continue Project Details


Earlier in this domain, you saw how a break statement is used to exit a Project Files:
block of code, specifically within a switch statement. You may need to 33d-practice-break.htm
do this within a loop as well, as a loop may reach a condition to where
the loop needs to be exited.
Estimated Completion
For situations in which you do not need to exit a loop but rather you Time:
minutes
want to skip over the code within the iteration of a loop, use a continue
statement.
Video Reference:
Domain 3
Purpose:
Topic: Loops
Upon completing this project, you will be able to break code in a loop
Subtopic: Break; Continue
within an if statement.

Steps for Completion: Objectives Covered:


3 Decisions and Loops
3.3 Complete and debug loops
3.3.e 3.e Break
3.3.f 3.f Continue

44 | Domain 3 JavaScript Project Workbook


1. Open the 33d-practice-break.htm file from the Music3 Student folder.
2. Replace the comment, // add condition, with a condition checking to see if the lessonStartDate equals
the breakDate.
3. Replace the comment, // exit the loop if the condition is true, with the keyword needed to exit the loop.
4. Save your changes.
5. Preview the webpage in a web browser.
6. Click in the Enter the number of hours per week field.
7. Type: 2 and press the Enter key. You should see no lessons after 11/20.
8. Return to your code editor.
9. Change the keyword used within the if statement to have the loop skip over the date if the condition is
true but not exit the loop completely.
10. Save your changes.
11. Preview the webpage in a web browser.
12. Click in the Enter the number of hours per week field.
13. Type: 2 and press the Enter key. You should see no lesson on 11/27 but a lesson on 12/4.
14. Close all of your open files in your browser and your code editor.

45 | Domain 3 JavaScript Project Workbook


Fill-in-the-Blanks Domain 4
Instructions: While watching Domain 4, fill in the missing words according to the information presented by
the instructor.
[References are found in the brackets.]

DOM Tree

1. A always starts with a Window project. [Window]

2. The document, every HTML element, and every descends from this document object.
[Document]

3. In the DOM, the two tags inside of the HTML tag are and body. [Body]

4. For the exam, know the starting point of a DOM and know how to a DOM. [Other HTML
Elements]

HTML Events

5. The onchange event fires when an is changed. [Onchange]

6. On objects, actions are often triggered through , [Onmouseover]

7. With an onload event, action is taken when an HTML loads. [Onload]

8. The two main actions taken as a result of an onclick event are a runs, or
within the event runs. [Onclick]

9. The onmouseout event triggers action when a mouse is moved from an object. [Onmouseout]

10. The onkeydown event triggers action when an item on the is pressed. [Onkeydown]

Output to HTML Documents


11. The innerHTML property allows us to control the text in between the opening and closing tag of an
existing HTML element . [InnerHTML]

12. The document.write method allows us to write both HTML elements and to a webpage.
[Document.Write]

Locate, Modify, and Add Elements

13. Once you get an element’s ID, you can change any of its using JavaScript. [GetElementById] 14.

The getElementsByTagName method will list elements and their . [GetElementsByTagName]

15. The classlist. property shows the number of times a class is being used.
[GetElementsByClassName]

47 | Domain 4 JavaScript Project Workbook


16. The first item in the array is item . [SetAttribute]

17. We can use the createElement method to place a new HTML element in a place on a
webpage.
[CreateElement]

Window Project Details

A window is a browser window that a user will interact with online. The Project Files:
window object contains properties such as height and width. The 41a-cart-DOM.htm
window object also contains objects such as the document and all
objects contained within a document. The basic structure of a window Estimated Completion
and its objects is known as the DOM (Document Object Model).
Time:
minutes
Purpose:
Upon completing this project, you will understand objects and their
Video Reference:
properties, how they relate to each other, and how they are used on a Domain 4
webpage. You will be able to start a Topic: DOM Tree
DOM. Subtopic: Window

Steps for Completion: Objectives Covered:


1. Name some properties of a Window object, besides height and 4 Document Object Model
width: 4.1 Identify and construct the
Document Object Model
(DOM) tree
2. Open the 41a-cart-DOM.htm file from the Music4 Student folder. 1.a Window
3. Find the checkoutWindow function.
4. Within the checkoutWindow function, add code to the window.open method to hide the status bar.
5. Save your changes.
6. Preview the webpage in a web browser.
7. Click the Checkout button. A checkout window should open and should not display a status bar.
8. Click the Close Checkout button. The checkout window should close.
Project Details
Document, Body, and Other Project Files:
HTML Elements 41b-tuningkits-DOM.htm

The document is a page of HTML or JavaScript code that will style a Estimated
webpage in a browser. The body is where the content code is found for Completion Time:
an HTML document. minutes

Purpose: Video Reference:


Upon completing this project, you will be able to identify a document Domain 4
and its main parts. Topic: DOM Tree
Subtopic: Document; Body;
Steps for Completion: Other HTML Elements
1. Open the 41b-tuningkits-DOM.htm file from the Music4 Student
folder. Objectives Covered:
4 Document Object Model
2. What is the first group of elements in the document? 4.1 Identify and construct the
Document Object Model
(DOM) tree
4.1.b 1.b Document
4.1.c Body
48 | Domain 4 JavaScript
4.1.d Project
Other Workbook
HTML
elements
3. What two tags are in the <html>element?

4. The head tag has which tags?

5. The link tag has what reference?

6. What are the sections of the body element?


7. Where would code for a paragraph tag be found?

Onchange Project Details

The onchange event usually happens when an object is immediately Project Files:
changed by an action. What sets this out as an event is that the user is 42a-practice-DOM.htm
interacting with the code through a keypress or mouse click. Or, an
onchange event can occur through a webpage loading or through an Estimated Completion
object changing a property, such as its value. Time:
minutes
Purpose:
Upon completing this project, you will know how an onchange event is Video Reference:
used in JavaScript. Domain 4
Topic: HTML Events
Steps for Completion: Subtopic: Onchange
1. Open the 42a-practice-DOM.htm file from the Music4 Student
folder. Objectives Covered:
2. Replace the HTML comment, <!-- call the getPracticeHours function 4 Document Object Model
when this field is changed -->, with a call to the getPracticeHours 4.2 Identify and handle
document, form, keyboard, and
function when the field changes.
mouse events
3. Save your changes. Onchange
4. Preview the webpage in a web browser.
5. Click in the Enter the number of hours field.
6. Type: 4 and press the Tab key. Notice the messages that appear as a result of your entering the
number of hours in a field.

Onmouseover Project Details

The onmouseover event triggers action when a user rolls a mouse over Project Files:
an object. A common use of this is the display of an image changing 42b-products-DOM.htm
when a user rolls a mouse over it.
Estimated Completion
Time:
Purpose: minutes
Upon completing this project, you will be able to create an
onmouseover event that will return a larger image in a separate image
element. Video Reference:
Domain 4
Topic: HTML Events
Steps for Completion: Subtopic: Onmouseover
1. Open the 42b-products-DOM.htm file from the Music4 Student
folder.
Objectives Covered:
2. Find the mouseOverPic function near the bottom of the page. Notice 4 Document Object Model
that the function uses a parameter for the image display. 4.2 Identify and handle
3. Scroll back up to the section on thumbnails. document, form, keyboard, and
mouse events
Onmouseover

49 | Domain 4 JavaScript Project Workbook


4. Replace the HTML comment, <!-- rollover mandolin-->, with a call to the mouseOverPic function, using
mandolin as a parameter, when the mouse rolls over the link.
5. Replace the HTML comment, <!-- rollover trombone-->, with a call to the mouseOverPic function,
using trombone as a parameter, when the mouse rolls over the link.
6. Replace the HTML comment, <!-- rollover drum-->, with a call to the mouseOverPic function, using
drum as a parameter, when the mouse rolls over the link.
7. Replace the HTML comment, <!-- rollover kazoo-->, with a call to the mouseOverPic function, using
kazoo as a parameter, when the mouse rolls over the link.
8. Replace the HTML comment, <!-- rollover musicbooks-->, with a call to the mouseOverPic function,
using musicbooks as a parameter, when the mouse rolls over the link.
9. Save your changes.
10. Preview the webpage in a web browser.
11. Roll your mouse over each of the thumbnail images. A larger version of the image should display as
you roll over each thumbnail.

Onload and Onclick Project Details

The onload event will return an action on the loading of an HTML Project Files:
element. The onload event is often used to call a function when a 42c-cart-DOM.htm
webpage loads.
Estimated Completion
An onclick event happens when an object or button is clicked and a Time:
code runs. The onclick event is the most frequently used event in minutes
JavaScript. The two main actions of an onclick event are that either a
function or a code within the event will run. Video Reference:
Domain 4
Purpose: Topic: HTML Events
Upon completing this project, you will be able to create an onload event Subtopic: Onload; Onclick
that will give an alert when a webpage is loaded.
Objectives Covered:
Steps for Completion: 4 Document Object Model
1. Open the 42c-cart-DOM.htm file from the Music4 Student folder. 4.2 Identify and handle
document, form, keyboard, and
2. In the body tag, create an onload event that will create an alert with mouse events
the text: This is an example of the onload event. 2.a Onload
3. Find the div tag with the class, itemquantity and the HTML 2.h Onclick
comments, <!-- run when clicked-->.
4. Within that div tag, replace each HTML comment with the event that triggers when each item is
clicked.
5. Save your changes.
6. Preview the webpage in a browser. An alert with the message you delivered should appear.
7. Close the alert.
8. Click the +, -, Clear, and Add Five buttons for the first two instruments. These buttons should, in
order, add one to the quantity, subtract one from the quantity, clear the quantity, and set the quantity
to five.

50 | Domain 4 JavaScript Project Workbook


Onmouseout Project Details

The onmouseout event is triggered and returns an action when a mouse Project Files:
moves away from an object. This is often used to display a message or 42e-cart-mouse.htm
change an object when a mouse moves away from an object.
Estimated Completion
Purpose: Time:
Upon completing this project, you will be able to create an onmouseout 5-10 minutes
event that will guide the user on page navigation.
Video Reference:
Steps for Completion: Domain 4
1. Open the 42e-cart-mouse.htm file from the Music4 Student folder. Topic: HTML Events
Subtopic: Onmouseout
2. Find the code for the div tag with the order_buttons class.
3. Replace the HMTL comment, <!--add instructions to click the button
when mouse moves away-->, with an alert function with the text, Objectives Covered:
Click the Update Cart button to update the order total, that 4 Document Object Model
4.2 Identify and handle
will occur when one moves the mouse away from the Update Cart
document, form, keyboard, and
button. mouse events
4. Save your changes. 2.j Onmouseout
5. Preview the webpage in a web browser.
6. Hover the mouse over the Update Cart button and then move away from the Update Cart button. You
should see an alert with instructions on how to use the Update Cart button.

Onkeydown Project Details

The onkeydown event will return an action if any key on the keyboard is Project Files:
pressed. This event is often geared toward users who would rather not 42f-cart-mouse.htm
use a mouse in order to trigger action. In addition, the event could be
used to push users toward using a mouse. Estimated Completion
A similar event, onkeyup, fires when a key on the keyboard is released. Time:
minutes
Purpose:
Upon completing this project, you will be able to create an onkeydown Video Reference:
event. Domain 4
Topic: HTML Events
Steps for Completion: Subtopic: Onkeydown
1. Open the 42f-cart-mouse.htm file from the Music4 Student folder.
2. Find the HTML comment, <!-- encourage mouse use --> Objectives Covered:
3. Replace the HTML comment that will, when a key is pressed down, 4 Document Object Model
dislay an alert with this text: It may be easier to use buttons to 4.2 Identify and handle
document, form, keyboard, and
change this field. mouse events
4. Save your changes. 2.e Onkeydown
5. Preview the webpage in a web browser.
6. Click in the Quantity field of the Mandolin and type: 5. You should see an alert explaining that it may
be easier to use buttons to change the field.
7. Close your open files, both in the browser and in your code editor.
8. Save the file as 42f-cart-mouse-finished.htm

51 | Domain 4 JavaScript Project Workbook


InnerHTML Project Details
The innerHTML property allows the text between the opening and Project Files:
closing tags to be dynamically controlled in an existing HTML element. 43a-practice-DOM.htm
It is important to know when to use the equal sign to replace content or
when to use the plus equal signs to append or add an attachment to
existing content. Changing the InnerHTML property allows the content Estimated Completion
of a page to be updated without the need to refresh the page. Time:
5-10 minutes

Purpose:
Upon completing this project, you will know when to change an Video Reference:
element’s innerHTML property. Domain 4
Topic: Output to HTML
Documents
Steps for Completion: Subtopic: InnerHTML
1. Open the 43a-practice-DOM.htm file from the Music4 Student
folder.
Objectives Covered:
2. Within the getPracticeHours function, replace both instances of the 4 Document Object Model
comment, // add code to set the element text, with the property and
4.3 Complete and debug code
operator necessary to set the text of each HTML element. that outputs to an HTML
3. Within the lessonSchedule function, replace both instances of the document
comment, // add code to append text to this element, with the 3.b InnerHTML
property and operator necessary to add the subsequent text to the
existing text within each HTML element.
4. Save your changes.
5. Preview the webpage in a web browser.
6. Click in the Enter the number of hours per week field.
7. Type: 10 and press the Enter key. You should see a message indicating when classes start. A total of
two class dates should be displayed.

Document.write Project Details

The document.write method allows you to write text and HTML Project Files:
elements dynamically to a webpage. The document.write method will 43b-cart-DOM.htm
overwrite existing content, so this is best to use on a webpage with no
content.
Estimated Completion
Time:
Purpose: minutes
Upon completing this project, you will be able to use the
document.write method to add content dynamically to a webpage.
Video Reference
Domain 4
Steps for Completion: Topic: Output to HTML
1. Open the 43b-cart-DOM.htm file from the Music4 Student folder. Documents
2. Find the checkoutWindow function near the bottom of the page. Subtopic: Document.write

3. Replace the comment, // add text to the new window, with a


statement that adds the text, This document is current as of Objectives Covered:
plus the current date. Make sure this is placed inside of a paragraph 4 Document Object Model
tag. 4.3 Complete and debug code
that outputs to an HTML
4. Save your changes. document
5. Preview the webpage in a web browser. 3.a Document.write

52 | Domain 4 JavaScript Project Workbook


6. Click the Checkout button. A small checkout window should appear with the message you configured
in this project.
7. Click the Close Checkout button to close the window.
8. Close all of your open files in your editor and web browser.

GetElement Project Details

There are three ways in which JavaScript works with elements to set Project Files:
properties and run methods. They are: 44a-comparison-get.htm

getElementById: elements are coded through using the element


ID. Using an element ID is the easiest way to locate an element in Estimated Completion
JavaScript. It is a good practice to assign an ID to all HTML elements Time:
that can be used in JavaScript code. It is important to have a minutes
consistent set of rules for creating ID names for your elements.
getElementByTagName: a method that allows you to get all the
Video Reference:
elements of a HTML tag. In most cases, this is used for testing
Domain 4
purposes, so you will want to list how many elements are in the
Topic: Output to HTML
document. A getElementByTagName method stores a set of values Documents
in an array. Subtopic: GetElementById;
getElementByClassName: a method that allows you to know what GetElementByTagName;
classes are in the document, and how many times a class is used. GetElementByClassName
This will help in determining if a class attribute should be changed.
Objectives Covered:
Purpose: 4 Document Object Model
Upon completing this project, you will know how to use getElementById, 4.4 Complete and debug code
getElementByTagName, and getElementByClassName. that locates, modifies, and
adds HTML elements and
attributes to documents
Steps for Completion: 4.4.a 4.a
1. Open the 44a-comparison-get.htm file from the Music4 Student GetElementById
folder. 4.4.b 4.b
GetElementByTagName
2. Replace the comment, // get all of the images, with a method used 4.4.c GetElementByClas
that will get all instances of the img tag. sName
3. Replace the comment, // get all of the social class instances, with a
method that will get all instances of the social class.
4. Replace the comment, // get sitelogo element, with the method that will get the element with an ID of
sitelogo.
5. Save your changes.
6. Preview the webpage in a web browser.
7. Click the Get Images button. A list of images for the webpage should display.
8. Click the Get Social Classes button. A number 1 should appear, indicating that the social class is used
once on the page.

53 | Domain 4 JavaScript Project Workbook


SetAttribute and Project Details

CreateElement Project Files:


44d-comparison-get.htm
The setAttribute method allows for a dynamic change of an element’s
attributes such as a class on an element through an onclick event. This Estimated Completion
is often used to allow a user to change the style of an element to make Time:
it more readable. minutes

The createElement method allows an element to be dynamically Video Reference:


created and placed in a specific spot on a webpage. The new element is Domain 4
placed within an element that has an ID and can be called through the Topic: Output to HTML
getElementById method. Once an element is created, one way in which Documents
text can be added to it is through the createTextNode method, which Subtopic: SetAttribute;
creates content to be added to the new element, and then the content CreateElement
is added through the appendChild method.
Objectives Covered:
A user can also interact with a webpage using event handlers and 4 Document Object Model
listeners in JavaScript. An event refers to actions by the user or actions 4.4 Complete and debug code
by the browser. Some common events include 'onload', 'onclick', and that locates, modifies, and
'onchange'. The 'onclick' event is commonly used for buttons or input adds HTML elements and
fields, while the 'onload' event is commonly used on a webpage's body attributes to documents
tag to execute code when a webpage has finished loading. 4.4.d SetAttribute
4.4.e 4.e CreateElement
An event listener or event handler specifies the event it is listening for 4.5 Create events using event
and the action (function) that will take place should that event occur. handlers and listeners
For example, an event listener can listen for a click on an HTML element 4.5.a 5.a DOM events
and then run a function. That function can then retrieve data, like the 4.5.b 5.b HTML attribute
current date, and insert that data into other HTML elements or event
JavaScript code. 4.5.c AddEventListener

Purpose:
Upon completing this project, you will be able to use the setAttribute method to allow the user to change
a heading style.

Steps for Completion:


1. Open the 44d-comparison-get.htm file from the Music4 Student folder.
2. In the setAltHeadingClass function, replace the comment, // set the class to altheading, with the code
necessary to change the class of the element in the function to altheading.
3. In the addConstructionMsg function, do the following:
a. Replace the comment, // create a paragraph element, with the
code necessary to create a new paragraph element.
b. Replace the comment, // add this text node, with the method
used to add the subsequent text as a new text node.
c. Replace the comment, // add text node to variable, with the code
necessary to add the constructionText content to the
constructionP variable.
d. Replace the comment, // add variable to element, with the code
necessary to add the constructionP element to the element with
an ID of sitelogo.

54 | Domain 4 JavaScript Project Workbook


4. Save your changes.
5. Preview your webpage in a web browser.
6. Click the Change Heading button. The style of the heading should change.
7. Click the Create Element button. A new text message should appear on the page.
8. Close all of your open files in your code editor and your web browser.

55 | Domain 4 JavaScript Project Workbook


Fill-in-the-Blanks Domain 5
Instructions: While watching Domain 5, fill in the missing words according to the information presented by
the instructor.
[References are found in the brackets.]

Retrieve Input and Set Form Field Values

1. Input tags with typically do not have innerHTML text. [Retrieve Form Values]

2. We can get a value of an individual field at any time through the method. [DOM Path]

3. Though this is a different type of element, we are still using the attribute to retrieve what was
chosen. [Values from Elements]

4. Prepopulating a field is a good practice for when a field is the same for virtually every entry.
[Prepopulating Values]

5. Setting an input field to a type field will mask the field. [Masking Values]

Input Validation
6. With fields, you may want consistent casing no matter how data is entered. [Upper and Lower Case]

7. JavaScript is a language, even for values in form fields. [String Comparisons]

8. Some form validation can take place without , as simple HTML can be used instead.
[Validation]

9. In JavaScript NaN means Not a . [NaN]

Form Submission Process

10. You can add multiple to an onsubmit event to validate a form. [Onsubmit]

11. When a form is processed, a for processing the form data is specified, right in the form tag.
[Understand Post vs. Get]

12. The target is defined in the attribute of the form tag. [Understand Potential Submission Targets]

57 | Domain 5 JavaScript Project Workbook


Retrieving Form Values Project Details

When a form is created, the information that is filled out will need to be Project Files:
accessed. An input tag does not have the innerHTML attribute, so the 51a-contact.htm
value attribute is used to retrieve the form information that was entered
in an input field. Estimated
Completion Time:
Purpose: 5-10 minutes
Upon completing this project, you will be able to use the value attribute
to retrieve the first and last name entered in an input field. Video Reference:
Domain 5
Steps for Completion: Topic: Retrieve Input and
Set Form
1. Open the 51a-contact.htm file from the Music5 Student folder.
Field Values
2. Within the fillTestResults function, replace the comment, // get what Subtopic: Retrieve Form
the user typed in for a first name, with a method that will retrieve Values
what the user typed into the firstname input field in the form.
3. Replace the comment, // get what the user typed in for a last name, Objectives Covered:
with a method that will retrieve what the user typed into the 5 HTML Forms
lastname input field in the form. 5.1 Complete and debug
4. Save your changes. code that retrieves form
input and sets form field
5. Preview the webpage in a web browser. values
6. Enter a first name and last name in the First and Last name fields. 1.a Retrieve form values

7. Click the Test form button. You should see a message with the name display.

DOM Path Project Details


JavaScript can access forms or form elements directly with the DOM Project Files:
path. When accessing forms in the Console, document.forms is an array 51b-contact.htm
that will start with the number zero. Each form has an array of
elements, through the document.forms.elements property, with the
array of elements for each form starting at zero. Estimated
Completion Time:
minutes
Purpose:
Upon completing this project, you will be able to follow the DOM path in
the Console to pull up elements and values. Video Reference:
Domain 5
Topic: Retrieve Input and
Steps for Completion: Set Form Field Values
1. Open the 51b-contact.htm file from the Music5 Student folder in a Subtopic: DOM Path
web browser.
Objectives Covered:
5 HTML Forms
5.1 Complete and debug
code that retrieves form
input and sets form field
values
1.b Identify the DOM path

58 | Domain 5 JavaScript Project Workbook


2. Open the Console.
3. Use the Console to list all the forms on this webpage. How many forms are on the webpage?
4. What is the ID of the first form?
5. Use the Console to list all of the elements on the first form of the page. How many elements are on
the form?
6. How many input elements are on the form?

Values from Elements Project Details

When a form is created, the information that is filled out will need to be Project Files:
accessed. Forms are made of input fields and elements and a value is 51c-contact.htm
typed into a field, selected from a drop-down list, or assigned through
one or more options, such as a single radio button or one or more check Estimated
boxes. Completion Time:
5-10 minutes
Purpose:
Upon completing this project, you will be able to retrieve a value from Video Reference:
an element and access the selected information. Domain 5
Topic: Retrieve Input and
Set Form
Steps for Completion:
Field Values
1. Open the 51c-contact.htm file from the Music5 folder. Subtopic: Values from
2. In the fillTestResults function, following the firstName and lastName Elements
variables, create a variable named found that will contain the value
from the found field. Objectives Covered:
3. Add, to the testResults.innerHTML property, the text: You found us 5 HTML Forms
via, a space, the found variable, and a period. 5.1 Complete and debug
code that retrieves form
4. Save your changes.
input and sets form field
5. Preview the webpage in a web browser. values
6. Enter a first and last name and select a field for the How did you Get values form different
types of elements
hear about us field.
7. Click the Test form button. You should see a message on the page with your name and the choice you
made in the found field.

Prepopulating Values Project Details

A prepopulated field will require less input for a user. The field will need Project Files:
to give the same exact answer in every instance to set a prepopulated 51d-contact.htm
answer. A field is often prepopulated through the use of an if or if-else
statement. Estimated
Completion Time:
minutes

Video Reference:
Domain 5
Topic: Retrieve Input and
Set Form
Field Values
Subtopic: Prepopulating
Values

Objectives Covered:
5 HTML Forms
5.1 Complete and debug
code that retrieves form
input and sets form field
59 | Domain 5 JavaScript Project Workbook
values
Prepopulate values
Purpose:
Upon completing this project, you will be able to set a field to prepopulate an answer based on an entry in
another field.

Steps for Completion:


1. Open the 51d-contact.htm file from the Music5 Student folder.
2. Within the fillState function, replace the comment, // add city and state logic, with code that will do
the following:
a. Assign a value of UT to the state variable if someone enters Salt Lake City for a
location.
b. Assign a value of NV to the state variable if someone enters Summerlin for a location.
c. Leaves the state variable blank if any other city value is chosen.
3. Within the city element, call the fillState function when an option is chosen, using the city indicated as
a parameter for each option with a city.
4. Save your changes.
5. Preview the webpage in a web browser.
6. Select Salt Lake City for a location. The state should change to UT.
7. Select Summerlin for a location. The state should change to NV.

Masking Values Project Details

Sensitive information such as Social Security numbers can make a user Project Files:
nervous to enter the information into an input field, so it is a best 51e-contact.htm
practice to mask the sensitive values being entered. When masking a
value, the value will be replaced with dots or another symbol instead of Estimated
the value being entered. A password type field will mask a field. Completion Time:
minutes
Purpose:
Upon completing this project, you will be able to mask a field value Video Reference:
using a password type field. Domain 5
Topic: Retrieve Input and
Steps for Completion: Set Form
Field Values
1. Open the 51e-contact.htm file from the Music5 Student folder.
Subtopic: Masking Values
2. In the password field code on line 104 of the code, change the type
from text to password
Objectives Covered:
3. Save your changes. 5 HTML Forms
4. Preview the webpage in a web browser. 5.1 Complete and debug
code that retrieves form
5. Begin to type in the password field. You should see masked
input and sets form field
characters. values
1.e Mask values

60 | Domain 5 JavaScript Project Workbook


6. Close all of your open files in your code editor and web browser.

Uppercase and Lowercase Project Details

JavaScript is a case-sensitive language. There will be instances where Project Files:


consistent casing will be needed in a form field. Text can be converted 52a-contact.htm
to its uppercase or lowercase equivalent at any time using the
toUpperCase and toLowerCase methods, respectively. This is a common Estimated Completion
tactic used to compare strings to a condition. As an example, if you are Time:
looking for a match to a city, such as Springfield, you could convert minutes
springfield, Springfield, or SPRINGFIELD to all lowercase or all uppercase
and then use that value in a condition.
Video Reference:
Domain 5
Purpose: Topic: Input Validation
Upon completing this project, you will be able to set the text of a form Subtopic: Upper and Lower
field to return in uppercase or lowercase and then use these in a Case; String Comparisons
conditional statement.
Objectives Covered:
Steps for Completion: 5 HTML Forms
1. Open the 52a-contact.htm file from the Music5 Student folder. 5.2 Complete and debug
code that performs input
2. Within the convertUpper function, replace the comment, // convert validation
to upper, with the code necessary to convert the text variable to an 5.2.a 2.a Case
uppercase value. 5.2.b 2.b String
3. Within the convertLower function, replace the comment, // convert comparisons
to lower, with the code necessary to convert the text variable to a lowercase value.
4. Within the checkCity function, replace the comment, // make the city variable uppercase, wih the code
necessary to set the city variable to an uppercase version of itself.
5. Save your changes.
6. Preview the webpage in a web browser.
7. Click in the State field.
8. Type nv and press the Tab key. Notice that the value converts to uppercase.
9. Click in the City field.
10. Type las vegas and press the Tab key. A message about the Summerlin location should appear at the
bottom of the page.

Validation Project Details

Valid data needs to be entered on a form before the form is submitted. Project Files:
The two tasks of validation are to check that required fields have 52c-contact.htm

Estimated Completion
Time:
minutes

Video Reference:
Domain 5
Topic: Input Validation
Subtopic: Validation

Objectives Covered:
5 HTML Forms
5.2 Complete and debug
code that performs input
validation
Not blank

61 | Domain 5 JavaScript Project Workbook


data/value entered and that the data/value entered is a legitimate value. There are form validations that
do not require JavaScript, such as an email field.

Purpose:
Upon completing this project, you will be able to add validations to fields.

Steps for Completion:


1. Open the 52c-contact.htm file from the Music5 Student folder.
2. Make the input element with an ID of zip a required field.
3. Add a call to the checkFields function within the button with the name, testForm.
4. Within the checkFields function, replace the comment, // add operator, with the operator necessary to
check and make sure neither the firstName nor lastName fields are empty.
5. Save your changes.
6. Preview the webpage in a web browser.
7. Click the Test Form button. You should see a message indicating that one or more required name fields
is empty.
8. Fill out the First Name, Last Name, and Zip fields.
9. Click the Test Form button. A message should appear at the bottom of the form.

NaN Project Details

NaN means Not a Number and will display when a calculation that Project Files:
expects a number takes place, but the calculation return is not a 52d-practice-DOM.htm
number. The written form of a number is not used in calculations, so
fields that make calculations should be set to require a number input. Estimated Completion
The NaN indicator can be corrected by validation or user training. Time:
5-10 minutes
Purpose:
Upon completing this project, you will better understand the cause of a Video Reference:
NaN message to appear. Domain 5
Topic: Input Validation
Steps for Completion: Subtopic: NaN
1. Open the 52d-practice-DOM.htm file from the Music5 Student
folder in a web browser. Objectives Covered:
5 HTML Forms
2. What does NaN stand for?
5.2 Complete and debug
3. Click in the Enter the number of hours per week field. code that performs input
validation
4. Type three and press the Enter key. Does NaN appear in the
NaN
message?

62 | Domain 5 JavaScript Project Workbook


5. What is the cause of the NaN indicator?

6. What can be done to correct a NaN?


7. Close all open files in your browser and code editor.

Onsubmit Project Details

The onsubmit event is used to run the last code before a form submits Project Files:
data to be processed. The most common use of the onsubmit event is 53a-contact.htm
the use of one or more functions used to validate a form. One onsubmit
event can use multiple functions. Estimated Completion
Time:
Purpose: minutes
Upon completing this project, you will be able to create an onsubmit
event that uses existing functions to validate form fields on a form.
Video Reference:
Domain 5
Steps for Completion: Topic: Form Submission Process
1. Open the 53a-contact.htm file from the Music5 Student folder. Subtopic: Onsubmit
2. In the opening form tag, replace the comment, <!-- add code to run
checkFields-->, with code that will run the checkFields function when Objectives Covered:
the form is submitted. 5 HTML Forms
3. Save your changes. 5.3 Describe the form
submission process
4. Preview the webpage in a web browser. 3.a Onsubmit
5. Click the Send It button. You should get a message indicating that
the zip field is required.

Post vs. Get and Submission Project Details

Project Files:
Targets 53b-contact.htm

The two methods used to process data are post and get. Post is used
when information is posted in an area. Get is used when you are trying
Estimated Completion
to get information, typically used for a search engine. The method for Time:
5-10 minutes
processing is in the form tag. The get method will publish terms a user
enters in the URL, so do not use this method if data needs to be kept
secure. Video Reference:
Domain 5
Regarding potential submission targets for data on a form, there are Topic: Form Submission Process
three common targets: Subtopic: Understand Post
vs. Get;
Understand Potential
Submission Targets

Objectives Covered:
5 HTML Forms
5.3 Describe the form
submission process
5.3.b 3.b Post vs. get
5.3.c Potential targets
for submission

63 | Domain 5 JavaScript Project Workbook


Database: data can be added to a database, or, as in the case of a search engine, data can be used
to look up a database to return matches.
Script: the data can be directed to a script file for further processing. The script file is a go-between
for a webpage submitting data to a data source, such as a database. Many of these scripts are server-
side scripts that use a variety of programming languages, such as C# or Python.
Webpage: the data can be processed on another webpage. That webpage could have direct access to
a database.

Purpose:
Upon completing this project, you will understand the post and get methods and how to write them in
code. You will also gain an understanding of the use of potential submission targets.

Steps for Completion:


1. Open the 53b-contact.htm file from the Music5 Student folder.
2. In the opening form tag, replace the comment, <!-- add submission method-->, with code to indicate
that this form will use the post method to process the data.
3. Save your changes.
4. Preview the webpage in a web browser.
5. Click the Send it button. You should see a message that the zip field, a required field, needs to be filled
out.
6. Looking at this form, what would be the most likely submission target used for the data?

7. Close all of your open files in your browser and code editor.
8. Close your browser and your code editor.

64 | Domain 5 JavaScript Project Workbook

You might also like