JavaScript Programming/Collection

JavaScript ProgrammingEdit


JavaScript, often abbreviated as JS, is a high-level, interpreted programming language that conforms to the ECMAScript specification. It is a programming language that is characterized as dynamic, weakly typed, prototype-based and multi-paradigm.[1]

Alongside HTML and CSS, JavaScript is one of the core technologies of the World Wide Web. JavaScript enables interactive web pages and is an essential part of web applications. The vast majority of websites use it, and major web browsers have a dedicated JavaScript engine to execute it.[2]

This course comprises 16 lessons on JavaScript programming. Each lesson includes a combination of Wikipedia and Internet-based readings, YouTube videos, and hands-on learning activities. The entire course can be downloaded in book form by selecting Download Learning Guide in the sidebar.

PreparationEdit

This is a second-semester, college-level course. Learners should already be familiar with introductory web development concepts, including HTML and CSS, and have advanced or proficient-level computer skills.

LessonsEdit

  1. Introduction
  2. Variables and Expressions
  3. Functions
  4. Events
  5. Conditions
  6. While Loops
  7. For Loops
  8. Arrays
  9. Date and Time
  10. Objects
  11. DOM and BOM
  12. Dynamic HTML
  13. Forms and Security
  14. AJAX and JSON
  15. Libraries and Frameworks
  16. Node.js REST API

See AlsoEdit

ReferencesEdit

Lesson 1 - IntroductionEdit

This lesson introduces the JavaScript programming language and environments.


Objectives and SkillsEdit

Objectives and skills for this lesson include:[1]

  • Apply JavaScript best practices
    • Comments; indentations; naming conventions; noscript; constants; reserved keywords; debugger keyword; setting breakpoints; console.log
  • Evaluate the use of inline and external scripts
    • When to use, how to use, and what happens when both are used

ReadingsEdit

  1. Wikibooks: JavaScript/Introduction
  2. Wikibooks: JavaScript/First program
  3. Wikibooks: JavaScript/Placing the code

MultimediaEdit

  1. YouTube: JavaScript Tutorial for Beginners - 01 - Introduction
  2. YouTube: JavaScript Tutorial for Beginners - 02 - Statements
  3. YouTube: JavaScript Tutorial for Beginners - 05 - Using an external file
  4. YouTube: JavaScript Tutorial for Beginners - 48 - Placement of script tag
  5. YouTube: JavaScript - Output
  6. YouTube: Beginner JavaScript Tutorial - 2 - Comments and Statements
  7. YouTube: JavaScript - How to use the console in a browser
  8. YouTube: noscript Tag - JavaScript Programming
  9. YouTube: Using Alert & Console.log in JavaScript
  10. YouTube: JavaScript Loading Strategies: Using the async and defer Attributes
  11. YouTube: Clean Code: Formatting and Comments
  12. YouTube: Javascript The innerHTML property

ExamplesEdit

ActivitiesEdit

  1. Create a web page that uses JavaScript to display Hello <name>!, where <name> is your name. Test JavaScript output in a variety of ways:
    • Use document.write()
    • Use window.alert()
    • Use document.getElementById().innerText or document.getElementById().innerHTML
    • Use console.log()
          Use your browser's built-in web development tools to view console output.
      • To open the console panel in Chrome press Ctrl+Shift+J (or Command+Option+J on Mac).[2]
      • To open the console panel in Firefox press Ctrl+Shift+J (or Command+Shift+J on a Mac).[3]
      • To open the console panel in Internet Explorer press F12 and then Ctrl+2.[4]
      • To open the console panel in Safari press Option-Command-I in the Develop Menu and click on the Console tab.[5]
  2. Using the Hello program above, test JavaScript code placement in a variety of ways:
    • Use <script> in <head> for the document.write()
    • Use <script> in <body> for the window.alert()
    • Use <script src=...> in <head> or <body> for the document.getElementById().innerText or document.getElementById().innerHTML and console.log()
  3. Add comments to the external JavaScript src code above, describing the program.
  4. Add a <noscript> section to the Hello html page above, displaying an appropriate message to users who have JavaScript disabled. Disable JavaScript in your browser to test the noscript section, then re-enable JavaScript.
  5. Research best practices for where to place JavaScript code and how to format and structure it (style guides).
  6. Research the difference between <script async ...> and <script defer ...>.

Lesson SummaryEdit

  • JavaScript, often abbreviated as JS, is a high-level, interpreted programming language that conforms to the ECMAScript specification.[6]
  • JavaScript comments are created using either // for single-line comments or /* ... */ for block comments.[7]
  • The HTML <noscript> element defines a section of HTML to be inserted if a script type on the page is unsupported or if scripting is currently turned off in the browser.[8]
  • The HTML <script> element is used to embed or reference executable code, and is typically used to embed or refer to JavaScript code.[9]
  • <script src="..."> specifies the URI of an external script and is used as an alternative to embedding a script directly within a document.[10]
  • JavaScript scripts required during the loading of the page are added to the document head section.[11]
  • JavaScript scripts not required during the loading of the page are added at the end of the document body section.[12]
  • JavaScript's best practice is to use external JavaScript files and load them at the end of the document body section.[13] Alternatively, external JavaScript files may be added at the end of the document head section and loaded asynchronously using the async or delay attributes.[14]
  • The async attribute indicates that the browser should, if possible, load the script asynchronously. The script is executed as soon as it is loaded.[15]
  • The defer attribute indicates that the browser should, if possible, load the script asynchronously. The script is executed after the document has been parsed.[16]
  • The Document.write() method writes a string of text to a document stream.[17]
  • The Window.alert() method displays an alert dialog with the optional specified content and an OK button.[18]
  • The document.getElementById() method returns an Element object representing the element whose id property matches the specified string.[19]
  • The Element innerHTML property gets or sets the HTML or XML markup contained within the element.[20]
  • The HTMLElement innerText property represents the text content of a node and its descendants.[21]
  • The console.log() method outputs a message to the web console.[22]

Key TermsEdit

comments
Used in programming languages, it allows the programmer to explain the code in a more understandable way to others. In JavaScript, there are two types of comments that can be created which includes single-line comments and block comments.[23]
ECMAScript
A scripting-language specification, standardized by Ecma International, which was created to standardize JavaScript and foster multiple independent implementations.[24]
external script
A script file that is attached to the HTML using the <script> element. Example - <script src='myscript.js'>.[source?]
statement
A command that performs an action. An example being, alert("string"), where alert prints the string within the parenthesis.[source?]

Review QuestionsEdit

  • What are three different ways to implement JavaScript into an HTML file?
  • What can you do with document.getElementById() in JavaScript?
  • How do you create a windowed message with JavaScript?
  • How do you embed JavaScript code in an HTML file?
  • What is <noscript> used for?

See AlsoEdit

ReferencesEdit

  1. Microsoft: Exam 98-382 Introduction to Programming Using JavaScript
  2. Chrome DevTools/
  3. MDNː Browser Console
  4. MSDNː Using keyboard shortcuts
  5. Safari Developer Helpː Developer Tools overview
  6. Wikipedia: JavaScript
  7. MDN: JavaScript Guide
  8. MDN: noscript
  9. MDN: script
  10. MDN: script
  11. MDN: Author Fast-Loading HTML Pages
  12. MDN: Author Fast-Loading HTML Pages
  13. MDN: Use JavaScript Within a Webpage
  14. MDN: script
  15. MDN: script
  16. MDN: script
  17. MDN: Document.write
  18. MDN: Window.alert
  19. MDN: Document.getElementById
  20. MDN: innerHTML
  21. MDN: innerText
  22. MDN: console.log
  23. "JavaScript Comments". www.w3schools.com. Retrieved 2020-08-26.
  24. Wikipedia: EMCAScript

Lesson 2 - Variables and ExpressionsEdit

This lesson introduces JavaScript variables, data types, expressions, and operators.


Objectives and SkillsEdit

Objectives and skills for this lesson include:[1]

  • Apply JavaScript best practices
    • Comments; indentations; naming conventions; noscript; constants; reserved keywords; debugger keyword; setting breakpoints; console.log
  • Declare and use variables of primitive data types
    • Number; Boolean; String; Null; Undefined; typeof operator; type checking functions; use strict; converting between data types; formatting numbers; string operations; single quote vs double quote (nesting); initialization
  • Complete or debug code that uses assignment and arithmetic operators
    • Assignment; increment; decrement; addition; subtraction; division; multiplication; modulus; compound assignment operators

ReadingsEdit

  1. Wikibooks: JavaScript/Variables and types
  2. Wikibooks: JavaScript/Numbers
  3. Wikibooks: JavaScript/Strings
  4. Wikibooks: JavaScript/Operators

MultimediaEdit

  1. YouTube: JavaScript Tutorial for Beginners - 03 - Variables
  2. YouTube: JavaScript Tutorial for Beginners - 04 - Variables Part 2
  3. YouTube: JavaScript Tutorial for Beginners - 08 - Operators
  4. YouTube: Javascript Variables & Data Types
  5. YouTube: JavaScript Let, Const & Var
  6. YouTube: A Basic Calculator
  7. YouTube: typeof Operator - JavaScript Tutorial
  8. YouTube: 20 String Methods in 7 Minutes
  9. YouTube: Debugging JavaScript (Google Chrome and Visual Studio Code)
  10. YouTube: Firefox JavaScript Debugger

ExamplesEdit

ActivitiesEdit

Complete the following activities using external JavaScript code. Apply JavaScript best practices, including comments, naming conventions, and constants. In at least one program, prompt the user for input and use console.log() for output. In another program, prompt the user for input and use document.getElementById().innerText or document.getElementById().innerHTML for output. Use the strict directive. Create test data to validate the accuracy of each program. Add comments at the top of the program and include references to any resources used.

ArithmeticEdit

  1. Create a program that uses variables for hours and rate per hour and then calculate and displays weekly, monthly, and annual gross pay (hours * rate). Base monthly and annual calculations on 12 months per year and 52 weeks per year.[2]
  2. Create a program that uses variables for years, and then calculate and displays an approximate age in months, days, hours, and seconds. For example, a person 1-year-old is 12 months old, 365 days old, etc.
  3. Review MathsIsFun: US Standard Lengths. Create a program that uses variables for a distance in miles, and then calculate and displays the distance in yards, feet, and inches, or calculate and display the distance in kilometers, meters, and centimeters.
  4. Review MathsIsFun: Area of Plane Shapes. Create a program that uses variables for the dimensions of different shapes and then calculate and displays the area of the shapes. Do not include shape choices. That will come later. For now, just include multiple shape calculations in sequence.
  5. Create a program that calculates the area of a room to determine the amount of floor covering required. The room is rectangular with the dimensions measured in feet with decimal fractions. The output needs to be in square yards. There are 3 linear feet to a yard.[3]
  6. Review MathsIsFun: Order of Operations. Create a program that demonstrates the order of operations. Include parentheses, exponents, multiplication, division, addition, and subtraction in your program. Use variables for the calculations and label the output. For example, part of the program might display:
        1 + 2 * 3 = 7
        (1 + 2) * 3 = 9
        ...

Data TypesEdit

  1. Create a program that initializes different variables with integer, floating point, string, null, and undefined values. Demonstrate various operations and converting between data types. For example, user input is always a string, but adding string values of "1" + "1" is typically "11", whereas, adding numeric values of 1 + 1 is 2. Use typeof to label each variable and the resulting output.
  2. Create a program that demonstrates string operations and string formatting. Define string constants or string literals that include apostrophes ('). Define string constants or string literals that include "quotes". Convert between string and numeric data types using Number() and .toFixed() with two decimal places. Concatenate string literals and variables to display output.

DebuggingEdit

  1. Use the debugger statement to create a breakpoint in one of the programs above. Experiment with single-stepping through the code and viewing script and global values. Add one or more variables to the watch window.
  2. Add a breakpoint to the program somewhere after the debugger statement. After the program stops with the debugger, resume script execution and observe the script stopping at the breakpoint.

Lesson SummaryEdit

  • By convention, JavaScript variable names are written in camelCase.[4]
  • JavaScript constant names are written in UPPER_CASE.[5]
  • JavaScript variable and constant names must be unique. These unique names are called identifiers.[6]
  • Reserved words (for example, continue, debugger, break, etc.) can't serve as variable names.[6]
  • Names can begin only with a letter, an underscore or a dollar sign. Names are allowed to contain numbers, but a number can't be the first character.[6]
  • In Java Script names are case sensitive.[6]
  • JavaScript has 7 data types: Number, String, Boolean, Null, Undefined, Function, and Object. Null and Undefined data types can't contain values.[7]
  • There are 6 types of objects in JavaScriptː Object, Date, Array, String, Number and Boolean.[7]
  • JavaScript has only 1 type of number.[8]
  • With some other languages, like Java and C, there is a special “character” type. JavaScript consists of only one type, string.[9]
  • The typeof operator is used to find the data type of the variable.[7]
  • JavaScript has built-in functions to work with strings and numbers[10]
  • Strings are written using single or double quotation marks. Quotation marks can be used inside the string if they don't match the ones outside of it.[7] Quotation marks used inside can match the outside ones only if they are preceded by the backslash escape character.[11]
  • You can convert between data types in JavaScript.[7]
  • "use strict" is a literal expression that requires / enforces variable declaration. It allows for cleaner code to be written.[12]

Key TermsEdit

array
An array is a type of variable that stores a collection of variables. Arrays in JavaScript are zero-based - they start from zero.[13]
assignment
Assigning a value to a variable or constant with the "=" operator.[source?]
Boolean
Data type which has only two values, True and False.[13]
camel case
Method of joining multiple words into one variable name where the first word is not capitalized and every subsequent word is capitalized.[source?]
concatenation
Method of joining two strings, data, or other text together in programming. In JavaScript, strings are concatenated using the '+' operator. [14]
console.log
A function in JavaScript which is used to print any kind of variables defined before in it or to just print any message that needs to be displayed to the user.[source?]
constant
A keyword introduced from ES2015, It is a container for storing a permanent data value that cannot be changed later in the program.[15]
let
A keyword introduced from ES2015, It is used to declare a variable in JavaScript. it is used as block scoped variable while "var" is used as a function scope variable [16]
null
A special value which represents "nothing." It is not a reference to a null pointer.[13]
number
Data type in JavaScript which represents both integers and floating-point value.[13]
object
A variable that can contain many values.[17]
order of operations
A set of rules for for evaluating mathematical expressions. While different programming languages have different rules for precedence, the order of operations start from greatest precedence with parentheses, exponents, multiplication/division, and addition/subtraction.[18]
string
Can consist of one character or many. A string must be surrounded by quotation marks.[13]
type coercion
The automatic or implicit conversion of values from one data type to another (such as strings to numbers).[19]
undefined
A variable which has not been assigned a value. If a variable is simply declared, but not assigned anything, it becomes undefined.[13]
variable
A container for storing a data values. Variables are used to hold values in expressions. [6]

See AlsoEdit

ReferencesEdit

Lesson 3 - FunctionsEdit

This lesson introduces JavaScript functions.


Objectives and SkillsEdit

Objectives and skills for this lesson include:[1]

  • Complete and debug code that uses built-in Math functions
    • Random; round; abs; floor; ceiling; min; max; pow; sqrt
  • Complete and debug a function that accepts parameters and returns a value
    • Reusable code; local versus global scope, redefine variables, pass parameters, value versus reference, return

ReadingsEdit

  1. Wikibooks: JavaScript/Functions
  2. Wikibooks: JavaScript/Anonymous functions

MultimediaEdit

  1. YouTube: JavaScript Tutorial for Beginners - 06 - Functions
  2. YouTube: JavaScript Tutorial for Beginners - 07 - Functions Part 2
  3. YouTube: JavaScript Tutorial for Beginners - 14 - Return statement
  4. YouTube: JavaScript Tutorial for Beginners - 15 - Global and local variables
  5. YouTube: JavaScript Tutorial for Beginners - 16 - Pass by value
  6. YouTube: JavaScript Pass By Reference
  7. YouTube: Number Methods and Math Objects in JavaScript
  8. YouTube: Javascript Functions & Parameters
  9. YouTube: JavaScript Functions - Practice
  10. YouTube: JavaScript Functions

ExamplesEdit

ActivitiesEdit

Complete the following activities using external JavaScript code. Apply JavaScript best practices, including comments, indentations, naming conventions, and constants. Prompt the user for input and use HTML elements for output. Use separate functions for each type of processing. Avoid global variables by passing parameters and returning results. Create test data to validate the accuracy of each program. Add comments at the top of the program and include references to any resources used.

  1. Create a program to prompt the user for hours worked per week and rate per hour and then calculate and display their weekly, monthly, and annual gross pay (hours * rate). Base monthly and annual calculations on 12 months per year and 52 weeks per year.[2]
  2. Create a program that asks the user how old they are in years, and then calculate and display their approximate age in months, days, hours, and seconds. For example, a person 1 year old is 12 months old, 365 days old, etc.
  3. Review MathsIsFun: US Standard Lengths. Create a program that asks the user for a distance in miles, and then calculate and display the distance in yards, feet, and inches, or ask the user for a distance in miles, and then calculate and display the distance in kilometers, meters, and centimeters.
  4. Review MathsIsFun: Area of Plane Shapes. Create a program that asks the user for the dimensions of different shapes and then calculate and display the area of the shapes. Do not include shape choices. That will come later. For now, just include multiple shape calculations in sequence.
  5. Create a program that calculates the area of a room to determine the amount of floor covering required. The room is rectangular with the dimensions measured in feet with decimal fractions. The output needs to be in square yards. There are 3 linear feet to a yard.[3]
  6. Create a program that helps the user determine how much paint is required to paint a room and how much it will cost. Ask the user for the length, width, and height of a room, the price of a gallon of paint, and the number of square feet that a gallon of paint will cover. Calculate the total area of the four walls as 2 * length * height + 2 * width * height Calculate the number of gallons as: total area / square feet per gallon Note: You must round up to the next full gallon. To round up, add 0.9999 and then convert the resulting value to an integer. Calculate the total cost of the paint as: gallons * price per gallon.[4]

Lesson SummaryEdit

  • A JavaScript function is a block of code designed to perform a particular task.[5]
  • Indent JavaScript code blocks (functions, conditions, loops, comment blocks, etc.) 2 spaces for each indent level.[6]
  • Functions break down code into reusable blocks of code each of which performs a specific task.[7]
  • Code inside a function is not executed at the time of declaration. A function has to be called upon (invoked) first.[8]
  • JavaScript function expressions can invoke themselves.[9]
  • JavaScript functions do not check the number of arguments received. Missing arguments are set to undefined.[10]
  • JavaScript functions do not check the data type of passed arguments.[10]
  • JavaScript functions can only return one value.[source?]

Key TermsEdit

anonymous function
A function that was declared without any named identifier to refer to it. As such, an anonymous function is usually not accessible after its initial creation.[11]
argument
The real value passed to (and received by) the function.[12]
arguments object
An array of the arguments passed in when the function is invoked. The arguments object can be used to access arguments when more arguments are passed to the function than parameters declared by the function definition.[13]
function
A block of code designed to perform a particular task when the code is invoked. A JavaScript function can be defined using the function keyword.[14]
function call
The declaration of the function by its self doesn't do anything. In order to execute that code, the function must be called using the name given when the function was declared, and parenthesis "()" with parameters if needed.[15]
function expression
A function that can be stored in a variable. After a function expression has been stored in a variable, the variable can be used as a function. Functions stored in variables do not need function names. They are always invoked (called) using the variable name.[16]
global variable
A variable declared outside a function.[17]
invocation
The code inside the function will execute when "something" invokes (calls) the function.[18]
local variable
A local variable is a variable which is either a variable declared within the function or is an argument passed to a function.[19]
parameter
A name listed in a function definition.[20]
return
Ends function execution and returns a value in the place the function was invoked.[21]
scope
Refers to the visibility of variables and methods in one part of a program to another part of that program (local and global variables).[22]
undefined
The undefined property indicates that a variable has not been assigned a value, or not declared at all. It is a variable in global scope.[23]

See AlsoEdit

ReferencesEdit

Lesson 4 - EventsEdit

This lesson introduces JavaScript events.


Objectives and SkillsEdit

Objectives and skills for this lesson include:[1]

  • Identify and handle HTML events
    • onchange; onmouseover; onload; onclick; onmouseout; onkeydown

ReadingsEdit

  1. Wikipedia: Event (computing)
  2. Wikibooks: JavaScript/Event handling
  3. Wikibooks: JavaScript/W3C event handlers

MultimediaEdit

  1. YouTube: What are JavaScript Events?
  2. YouTube: addEventListener()
  3. YouTube: JavaScript Tutorial for Beginners - 32 - Changing an image
  4. YouTube: JavaScript Tutorial for Beginners - 33 - Intro to events
  5. YouTube: JavaScript Tutorial for Beginners - 34 - The mouseover event
  6. YouTube: JavaScript Questions: What is Event Delegation, Event Propagation, Event Bubbling?

ExamplesEdit

ActivitiesEdit

Complete the following activities using external JavaScript code. Apply JavaScript best practices, including comments, indentations, naming conventions, and constants. Use input elements for input and respond to input or change events or add buttons and respond to click events. Use HTML elements for output. Use separate functions for each type of processing. Avoid global variables by passing parameters and returning results. Create test data to validate the accuracy of each program. Add comments at the top of the program and include references to any resources used.

  1. Create a program to prompt the user for hours worked per week and rate per hour and then calculate and display their weekly, monthly, and annual gross pay (hours * rate). Base monthly and annual calculations on 12 months per year and 52 weeks per year.[2]
  2. Create a program that asks the user how old they are in years, and then calculate and display their approximate age in months, days, hours, and seconds. For example, a person 1 year old is 12 months old, 365 days old, etc.
  3. Review MathsIsFun: US Standard Lengths. Create a program that asks the user for a distance in miles, and then calculate and display the distance in yards, feet, and inches, or ask the user for a distance in miles, and then calculate and display the distance in kilometers, meters, and centimeters.
  4. Review MathsIsFun: Area of Plane Shapes. Create a program that asks the user for the dimensions of different shapes and then calculate and display the area of the shapes. Do not include shape choices. That will come later. For now, just include multiple shape calculations in sequence.
  5. Create a program that calculates the area of a room to determine the amount of floor covering required. The room is rectangular with the dimensions measured in feet with decimal fractions. The output needs to be in square yards. There are 3 linear feet to a yard.[3]
  6. Create a program that helps the user determine how much paint is required to paint a room and how much it will cost. Ask the user for the length, width, and height of a room, the price of a gallon of paint, and the number of square feet that a gallon of paint will cover. Calculate the total area of the four walls as 2 * length * height + 2 * width * height Calculate the number of gallons as: total area / square feet per gallon Note: You must round up to the next full gallon. To round up, add 0.9999 and then convert the resulting value to an integer. Calculate the total cost of the paint as: gallons * price per gallon.[4]

Lesson SummaryEdit

  • Events are actions or occurrences that happen in the system you are programming[5]
  • Events occur when the user clicks a button, presses a key on the keyboard, submits a form, resizes the window, etc. JavaScript can detect and react to such events by executing the code.[6]
  • Each available event has an event handler, which is a block of code (usually a JavaScript function that you as a programmer create) that will be run when the event fires. [7]
  • For a start, it is not a good idea to mix up your HTML and your JavaScript, as it becomes hard to parse — keeping your JavaScript all in one place is better; if it is in a separate file you can apply it to multiple HTML documents.[8]
  • Event propagation is a way of defining the element order when an event occurs. If you have one element inside a second element, and the user clicks on the first element, which element's "click" event should be handled first?[9]
  • In bubbling the innermost element's event is handled first and then the outer.[10]
  • In capturing the outer most element's event is handled first and then the inner[11]

Key TermsEdit

DOM (Document Object Model)
The HTML DOM model is constructed as a tree of objects. The DOM defines a standard for accessing documents.[12]
event
A function can be called when an event occurs such as the user clicking on an element. Some other examples of events in JavaScript are mouseover, mouseout, input, and onload.[13]
event handler
An event that can be handled is something happening in a browser window, including a document loading, the user clicking a mouse button, the user pressing a key, and the browser screen changing size. When a function is assigned to handle an event type, that function is run when an event of the event type occurs. Examples include "onclick" and "onmouseover"[14]
event listener
It is attached to an element and fires a function when the event is detected on the element. [15]
onchange
An HTML element has been changed.[16]
onclick
An HTML event when the user clicks an HTML element.[17]
onkeydown
An HTML event when the user pushes a keyboard key.[18]
onload
The browser has finished loading the page.[18]
onmouseout
The user moves the mouse away from an HTML element.[16]
onmouseover
An HTML event when the user moves the mouse over an HTML element.[16]

See AlsoEdit


ReferencesEdit

Lesson 5 - ConditionsEdit

This lesson introduces JavaScript conditions.


Objectives and SkillsEdit

Objectives and skills for this lesson include:[1]

  • Evaluate expressions that use logical and comparison operators
    • ==; !=; <, >; <=; >=; !; &&; ||
  • Complete and debug decision statements
    • if; else if; switch; nested if
  • Complete and debug code that performs input validation
    • Case; string comparisons; Not-A-Number (NaN)

ReadingsEdit

  1. Wikipedia: Structured programming
  2. Wikipedia: Conditional (computer programming)
  3. Wikibooks: JavaScript/Control structures

MultimediaEdit

  1. YouTube: How to Create Conditions in JavaScript | Conditional Statements | JavaScript Tutorial
  2. YouTube: Introduction to Conditional Statements - p5.js Tutorial
  3. YouTube: Javascript for Beginners - if, else if, else
  4. YouTube: JavaScript if - else Statement
  5. YouTube: How to use if/else conditions in JavaScript
  6. YouTube: JavaScript Tutorial for Beginners - 13 - Function and if statement
  7. YouTube: JavaScript Tutorial - Switch Statement
  8. YouTube: Switch - How to Use the JavaScript Switch Statement
  9. YouTube: How to Get a Value from a Radio Button using Javascript

ExamplesEdit

ActivitiesEdit

Complete the following activities using external JavaScript code. Apply JavaScript best practices, including comments, indentations, naming conventions, and constants. Use input elements for input and respond to input or change events or add buttons and respond to click events. Use HTML elements for output. Use separate functions for each type of processing. Avoid global variables by passing parameters and returning results. Create test data to validate the accuracy of each program. Add comments at the top of the program and include references to any resources used.

If ConditionsEdit

  1. Create a program to prompt the user for hours and rate per hour to compute gross pay (hours * rate). Include a calculation to give 1.5 times the hourly rate for any overtime (hours worked above 40 hours).[2]
  2. Create a program that asks the user how old they are in years. Then ask the user if they would like to know how old they are in (M)onths, (D)ays, (H)ours, or (S)econds. Use if/else conditional statements to display their approximate age in the selected timeframe. Do not perform any unnecessary calculations.
  3. Review MathsIsFun: US Standard Lengths. Create a program that asks the user for a distance in miles, and then ask the user if they want the distance in US measurements (yards, feet, and inches) or in metric measurements (kilometers, meters, and centimeters). Use if/else conditional statements to determine their selection and then calculate and display the results.
  4. Review MathsIsFun: Area of Plane Shapes. Create a program that asks the user what shape they would like to calculate the area for. Use if/else conditional statements to determine their selection and then gather the appropriate input and calculate and display the area of the shape.
  5. Create a program that helps the user determine what sock size to order based on their shoe size:
        < 4 = extra small
        4 to 6 = small
        7 to 9 = medium
        10 to 12 = large
        13+ = extra large
    Use if/else conditional statements to determine their selection and then display the results. Round half-sizes up to the next whole size. One option for rounding is to add 0.5 and then convert to an integer.[3]

Switch ConditionsEdit

  1. Create a program that asks the user how old they are in years. Then ask the user if they would like to know how old they are in (M)onths, (D)ays, (H)ours, or (S)econds. Use switch conditional statements to display their approximate age in the selected timeframe. Do not perform any unnecessary calculations.
  2. Review MathsIsFun: Area of Plane Shapes. Create a program that asks the user what shape they would like to calculate the area for. Use switch conditional statements to determine their selection and then gather the appropriate input and calculate and display the area of the shape.
  3. Create a program that helps the user determine what sock size to order based on their shoe size:
        < 4 = extra small
        4 to 6 = small
        7 to 9 = medium
        10 to 12 = large
        13+ = extra large
    Use switch conditional statements to determine their selection and then display the results. Round half-sizes up to the next whole size. One option for rounding is to add 0.5 and then convert to an integer.[4]

Input ValidationEdit

  1. Review Wikipedia: Is functions. Update one or more of the programs above to include input validation for all numeric input.
  2. Extend one or more of the programs above by adding structured exception handling statements (try-catch) to handle any runtime errors caused by the user entering invalid values for the input.

Lesson SummaryEdit

  • Conditional statements are used to perform different actions based on different decisions.[5]
  • The if statement is to specify a block of code to be executed, if a specified condition is true.[6]
  • The else statement is to specify a block of code to be executed, if the same condition is false.[7]
  • the else if statement is to specify a new condition to test, if the first condition is false.[8]
  • The switch statement is used to perform different actions based on different conditions.[9]
  • Break keyword is used to break down from the switch block. Once the match is found, and the associated code block is executed, the following cases are not being tested against the condition.[10]
  • The switch statement may have an optional default case. It specifies the block of code that runs if there is no case match.[10]
  • Conditional statements can be inside of other conditional statements, and can have multiple conditions to test.[source?]

Key TermsEdit

boolean
The boolean data type has one of two possible values (TRUE or FALSE) which is intended to represent the two truth values.[11]
break
Keyword that breaks out of the switch block. This will stop the execution of inside the block.[12]
comparison operators
Comparison operators are used in logical statements to determine equality or difference between variables or values.[13]
conditional statement
It is a condition that has to be fulfilled (true) to perform an action.[14]
default
Keyword that specifies the code to run if there is no case match.[15]
"else" statement
The else statement is to specify a block of code to be executed if the same condition is false.[16]
"else if" statement
The else if statement specifies a new condition if the first condition is not met.[17]
"if" statement
The if statement executes a statement if a specified condition is true. If the condition is false, the code within the If statement is ignored, and the code immediately after will run.[18]
logical operators
Logical operators are used to determine the logic between variables or values.[19]
nested if statement
An if statement inside another if statement (multiple if statements).[20]
switch
Used to select one of many code blocks to be executed based on evaluation of a single expression.[21]

See AlsoEdit

ReferencesEdit

Lesson 6 - While LoopsEdit

This lesson introduces JavaScript while and do while loops.


Objectives and SkillsEdit

Objectives and skills for this lesson include:[1]

  • Complete and debug loops
    • for; while; do; break; continue

ReadingsEdit

  1. Wikipedia: Control flow
  2. Wikibooks: JavaScript/Control structures

MultimediaEdit

  1. YouTube: JavaScript Tutorial for Beginners - 11 - Loops
  2. YouTube: JavaScript Tutorial for Beginners - 12 - Loops Part 2
  3. YouTube: freeCodeCamp.org While / Do While
  4. YouTube: 4.1: while and for Loops
  5. YouTube: JavaScript Tutorial For Beginners #16 - While Loops
  6. YouTube: JavaScript beginner tutorial 21 - do while loop
  7. While / Do While - Beau teaches JavaScript

ExamplesEdit

ActivitiesEdit

Complete the following activities using external JavaScript code. Apply JavaScript best practices, including comments, indentations, naming conventions, and constants. Use input elements for input and respond to input or change events or add buttons and respond to click events. Use HTML elements for output. Use separate functions for each type of processing. Avoid global variables by passing parameters and returning results. Create test data to validate the accuracy of each program. Add comments at the top of the program and include references to any resources used.

While LoopsEdit

Complete the following using a while loop structure.

  1. Create a program that uses a loop to generate a list of multiplication expressions for a given value. Ask the user to enter the value and the number of expressions to be displayed. For example, a list of three expressions for the value 1 would be:
        1 * 1 = 1
        1 * 2 = 2
        1 * 3 = 3
    A list of five expressions for the value 3 would be:
        3 * 1 = 3
        3 * 2 = 6
        3 * 3 = 9
        3 * 4 = 12
        3 * 5 = 15
  2. Review MathsIsFun: Pi. Write a program that uses the Nilakantha series to calculate Pi based on a given number of iterations entered by the user.
  3. Review MathsIsFun: Definition of Average. Create a program that asks the user to enter grade scores. Start by asking the user how many scores they would like to enter. Then use a loop to request each score using a prompt and add it to a total. Finally, calculate and display the average for the entered scores.
  4. Review MathsIsFun: Definition of Average. Create a program that asks the user to enter grade scores. Start by asking the user how many scores they would like to enter. Then request each score using an input element and add it to a total. Finally, calculate and display the average for the entered scores. In this approach, the loop action is performed by the user rather than by the code.

Do While LoopsEdit

Complete the following using a do while loop structure.

  1. Review MathsIsFun: Definition of Average. Create a program that asks the user to enter grade scores. Use a loop to request each score using a prompt and add it to a total. Continue accepting scores until the user enters no value (empty input). Finally, calculate and display the average for the entered scores.
  2. Review Khan Academy: A guessing game. Write a program that allows the user to think of a number between 0 and 100, inclusive. Then have the program try to guess their number. Start at the midpoint (50) and ask the user if their number is (h)igher, (l)ower, or (e)qual to the guess using a prompt. If they indicate lower, guess the new midpoint (25). If they indicate higher, guess the new midpoint (75). Continue efficiently guessing higher or lower until they indicate equal, then print the number of guesses required to guess their number and end the program.
  3. Review MathsIsFun: Definition of Average. Create a program that asks the user to enter grade scores. Request each score using an input element and add it to a total. Continue accepting scores until the user enters no value (empty input). Finally, calculate and display the average for the entered scores. In this approach, the loop action is performed by the user rather than by the code.
  4. Review Khan Academy: A guessing game. Write a program that allows the user to think of a number between 0 and 100, inclusive. Then have the program try to guess their number. Start at the midpoint (50) and ask the user if their number is (h)igher, (l)ower, or (e)qual to the guess using three buttons. If they indicate lower, guess the new midpoint (25). If they indicate higher, guess the new midpoint (75). Continue efficiently guessing higher or lower until they indicate equal, then print the number of guesses required to guess their number and end the program. In this approach, the loop action is performed by the user rather than by the code.

Lesson SummaryEdit

  • Loops are used to avoid code repetition. [2]
  • Loops are useful when aiming for DRY (Don't repeat yourself) solutions vs. WET (Write every time) solutions when programming. [3]
  • Four components of any loop are the initialization of a loop control variable, terminating condition, update step (increment or decrement), and a loop body. [4] [5]
  • Loop may run n number of times or may not run at all, depending on the condition.[2]
  • We get an infinite loop when we forget to include terminating condition, when the condition can never be met or if it makes the loop to start over and over again. [6]
  • A nested loop, or a loop inside of another loop, can be used to better structure code and make it maintainable.[source?]

Key TermsEdit

do while loop
This loop will execute the code block once, before checking if the condition is true, then it will repeat the loop as long as the condition is true.[7]
increment
The increment operator (++) increments (adds one to) its operand and returns a value.[8]
infinite loop
A loop that theoretically runs forever.[9]
iteration
It's a repetition of code or cycle, performed by a loop[10]
While loop
The while loop executes a block of code repeatedly as long as a specified condition is true.[11]

See AlsoEdit

ReferencesEdit

Lesson 7 - For LoopsEdit

This lesson introduces JavaScript for loops and nested loops.


Objectives and SkillsEdit

Objectives and skills for this lesson include:[1]

  • Complete and debug loops
    • for; while; do; break; continue

ReadingsEdit

  1. Wikipedia: Control flow
  2. Wikipedia: For loop
  3. Wikibooks: JavaScript/Control structures

MultimediaEdit

  1. YouTube: JavaScript Tutorial for Beginners - 28 - getElementsByTagName Part 2
  2. Youtube: For Loops | Javascript | Tutorial 23
  3. YouTube: For Loops - Beau teaches JavaScript
  4. YouTube: JavaScript Tutorial For Beginners #18 - Break & Continue
  5. YouTube: JavaScript Tutorials for Beginners - 9 - How to Code Nested For Loops with JavaScript
  6. Youtube: JavaScript Nested Loops

ExamplesEdit

ActivitiesEdit

Complete the following activities using external JavaScript code. Apply JavaScript best practices, including comments, indentations, naming conventions, and constants. Use input elements for input and respond to input or change events or add buttons and respond to click events. Use HTML elements for output. Use separate functions for each type of processing. Avoid global variables by passing parameters and returning results. Create test data to validate the accuracy of each program. Add comments at the top of the program and include references to any resources used.

For LoopsEdit

Complete the following using a for loop structure.

  1. Create a program that uses a loop to generate a list of multiplication expressions for a given value. Ask the user to enter the value and the number of expressions to be displayed. For example, a list of three expressions for the value 1 would be:
        1 * 1 = 1
        1 * 2 = 2
        1 * 3 = 3
    A list of five expressions for the value 3 would be:
        3 * 1 = 3
        3 * 2 = 6
        3 * 3 = 9
        3 * 4 = 12
        3 * 5 = 15
  2. Review MathsIsFun: Definition of Average. Create a program that asks the user to enter grade scores. Start by asking the user how many scores they would like to enter. Then use a loop to request each score and add it to a total. Finally, calculate and display the average for the entered scores.
  3. Review MathsIsFun: Pi. Write a program that uses the Nilakantha series to calculate Pi based on a given number of iterations entered by the user.

Nested LoopsEdit

Complete the following using a nested loop structure.

  1. Review MathsIsFun: 10x Printable Multiplication Table. Create a program that uses nested loops to generate a multiplication table. Rather than simply creating a 10 by 10 table, ask the user to enter the starting and ending values. Include row and column labels. For example, the output from 1 to 3 might look like:
            1   2   3
        1   1   2   3
        2   2   4   6
        3   3   6   9
    The output from 3 to 5 might look like:
            3   4   5
        3   9  12  15
        4  12  16  20
        5  15  20  25

Lesson SummaryEdit

  • Loops are used to avoid code repetition.[2]
  • Loops are useful when aiming for DRY (Don't repeat yourself) solutions vs. WET (Write every time) solutions when programming.[3]
  • Four components of any loop are the initialization of a loop control variable, terminating condition, update step (increment or decrement), and a loop body.[4][5]
  • Loop may run n number of times or may not run at all, depending on the condition.[2]
  • We get an infinite loop when we forget to include terminating condition, when the condition can never be met or if it makes the loop to start over and over again.[6]
  • Loops are handy, if you want to run the same code over and over again, each time with a different value.[7]
  • The basic structure for a for loop is: for (initialExpression, condition, increment) {loop body} ;[source?]
  • If you omit statement 2 (condition), you must provide a break inside the loop. Otherwise the loop will never end.[8]
  • Statement 3 (increment) can do anything like negative increment (i--), positive increment (i = i + 15), or anything else. Statement 3 can also be omitted.[9]
  • For loops can be run from n-n number of times (ie. 3-8) meaning you can skip the data for a set number of loops. This isn't possible with other loops.[source?]
  • Continue only skips one iteration in the loop, where as break statements leave the loop completely.[source?]

Key TermsEdit

break
A statement used to jump out of a loop.[10]
continue
A statement where it breaks one iteration (in the loop), if a specified condition occurs, and continues with the next iteration in the loop.[11]
for loop
Loops repeatedly executes a block of code a specified number of times.[12]
nested loops
A composition of loops is called a nested loop. The most common type of nested loops will be one loop inside another. The first loop is usually called the outer loop while the second loop is called the inner loop.[13]

See AlsoEdit

ReferencesEdit

Lesson 8 - ArraysEdit

This lesson introduces JavaScript arrays.


Objectives and SkillsEdit

Objectives and skills for this lesson include:[1]

  • Declare and use arrays
    • Single-dimensional arrays; multi-dimensional arrays; iteration; initialization; define an array; sort and search an array; use push, pop, shift, and unshift methods; use the length property; access an array element;

ReadingsEdit

  1. Wikipedia: Array data type
  2. Wikipedia: Dynamic array
  3. Wikibooks: JavaScript/Arrays

MultimediaEdit

  1. YouTube: JavaScript Tutorial for Beginners - 17 - Arrays
  2. YouTube: JavaScript Arrays with different data types
  3. YouTube: How to Create Arrays in JavaScript
  4. Youtube: JavaScript Tip: 7 Ways to Iterate Over an Array
  5. YouTube: Push, Pop, Unshift and Shift Array Methods
  6. YouTube: Multidimensional array tutorial

ExamplesEdit

ActivitiesEdit

Complete the following activities using external JavaScript code. Apply JavaScript best practices, including comments, indentations, naming conventions, and constants. Use input elements for input and respond to input or change events or add buttons and respond to click events. Use HTML elements for output. Use separate functions for each type of processing. Avoid global variables by passing parameters and returning results. Create test data to validate the accuracy of each program. Add comments at the top of the program and include references to any resources used.

  1. Extend any of the activities from JavaScript Programming/Loops to use an array to hold the information generated during processing (values only) and display the results from the array (add HTML formatting) after processing is complete.

Lesson SummaryEdit

  • The first element of the array has an index of 0. The second element has an index of 1. The last element has an index of arrayName.length - 1.[2]
  • JavaScript arrays are used to store multiple values in a single variable.[2]
  • An array that has multiple arrays in it is called a multi-dimensional array.[source?]

Key TermsEdit

array
Arrays allow us to store multiple values in a single variable.[3]
array methods
Built-in functions to work with arrays in JavaScript.[4]
index or subscript
An integer that defines an element position within an array and is used to access that element.[2]
length
The number of elements in an array.[5]
multi-dimensional array
An array whose elements consist of other arrays.[6]
pop() method
This method removes the last element from an array.[7]
push() method
Is the easiest way to add a new element to an array.[2]

See AlsoEdit

ReferencesEdit

Lesson 9 - Date and TimeEdit

This lesson introduces JavaScript objects using dates.


Objectives and SkillsEdit

Objectives and skills for this lesson include:[1]

  • Complete and debug code that uses objects
    • Properties; methods; instantiation; Date object; retrieve date and time parts; localize date format (MM/DD vs DD/MM); add and subtract dates

ReadingsEdit

  1. Wikibooks: JavaScript/Dates

MultimediaEdit

  1. YouTube: Date Objects
  2. YouTube: Display and Change the Time And Date With JavaScript
  3. YouTube: Date methods in JavaScript
  4. YouTube: Displaying the Current/Live Date & Time on a Web Page

ExamplesEdit

ActivitiesEdit

Complete the following activities using external JavaScript code. Apply JavaScript best practices, including comments, indentations, naming conventions, and constants. Use input elements for input and respond to input or change events, add buttons and respond to click events, or set a timer interval and respond to interval events. Use HTML elements for output. Use separate functions for each type of processing. Avoid global variables by passing parameters and returning results. Create test data to validate the accuracy of each program. Add comments at the top of the program and include references to any resources used.

  1. Create a web page to display the current date and time. Rather than displaying the date and time as a single string, use output elements and Date methods to separately display the year, month, day, hour, minute, and second. Set a timer interval so the current time updates automatically every second.
  2. Create a web page with a date picker (input type="date"). When a user selects a date, use output elements to separately display the selected month, day, and year. Be sure to account for UTC/time zone when displaying the selected date.
  3. Create a web page with a date picker (input type="date"). Add number fields (input type="number") that allow the user to add years, months, and days to the selected date. Limit additional months to 0-11. Limit additional days to 0-30. As the number fields change, use an output element to display the result of adding the given years, months, and days to the selected date.
  4. Create a web page with two date pickers (input type="date"). When a user selects both dates, use output elements to display the number of years, months, and days between the two dates.
  5. Use JavaScript Date.now() and loops to time two different ways to implement the same thing. For example, is it faster to use a local variable or update an HTML element on each loop iteration?

Lesson SummaryEdit

  • The Date object is used to work with dates and times.[2]
  • By default, JavaScript will use the browser's time zone and display a date as a full-text string.[3]
  • Date objects are created with the new Date() constructor, which can take parameters: year, month, day, hours, minutes, seconds, milliseconds.[3]
  • JavaScript stores dates as the number of milliseconds since Unix Epoch (January 01, 1970, 00:00:00 UTC).[3]
  • The JavaScript Date object has a list of get methods that can be used to get date's infomation such as day, hours, minutes, etc.[4]
  • The JavaScript Date object also has a list of set methods that can be used to set date's information in a Date object.[5]

Key TermsEdit

epoch Time
Epoch time or Unix time is a way to track time as a running total of seconds. This count starts at the Unix Epoch on January 1st, 1970 at UTC. Therefore, the Unix time stamp is merely the number of seconds between a particular date and the Unix Epoch.[6]
new date()
Returns a new Date object that represents the current date and time.[7]
prototype
Allows you to add properties and methods to an object.[8]
setInterval()
A method calls a function or evaluates an expression at specified intervals (in milliseconds).[9]
setTimeout()
A method calls a function or evaluates an expression after a specified number of milliseconds.[10]
UTC
The Universal Coordinated Time (UTC) is the time set by the World Time Standard.[11]

See AlsoEdit

ReferencesEdit

Lesson 10 - ObjectsEdit

This lesson introduces JavaScript objects.


Objectives and SkillsEdit

Objectives and skills for this lesson include:[1]

  • Complete and debug code that uses objects
    • Properties; methods; instantiation; Date object; retrieve date and time parts; localize date format (MM/DD vs DD/MM); add and subtract dates

ReadingsEdit

  1. Wikipedia: Associative array
  2. Wikibooks: JavaScript/Objects

MultimediaEdit

  1. YouTube: JavaScript Tutorial for Beginners - 18 - Objects
  2. YouTube: JavaScript Tutorial for Beginners - 19 - Objects Part 2
  3. YouTube: JavaScript Tutorial for Beginners - 20 - Objects Part 3
  4. YouTube: JavaScript Tutorial for Beginners - 21 - Objects Part 4
  5. YouTube: JavaScript Tutorial for Beginners - 22 - String Object
  6. YouTube: JavaScript Tutorial for Beginners - 51 - More on Objects
  7. YouTube: An Encounter with JavaScript Objects

ExamplesEdit

ActivitiesEdit

Complete the following activities using external JavaScript code. Apply JavaScript best practices, including comments, indentations, naming conventions, and constants. Use input elements for input and respond to input or change events, add buttons and respond to click events, or set a timer interval and respond to interval events. Use HTML elements for output. Use separate functions for each type of processing. Avoid global variables by passing parameters and returning results. Create test data to validate the accuracy of each program. Add comments at the top of the program and include references to any resources used.

  1. Create a web page that allows the user to enter book information for a bibliography. Include properties for title, author, year, publisher, city, and state. Respond to one or more user interface events to create an instance of a Book object and then display the book properties in APA format:[2]
         Last, F. M. (Year) Title. City, State: Publisher.
  2. Extend the program above by adding an APA method to your object that automatically formats the book for display. Use the APA method to format output, replacing the display code above.
  3. Extend the program above by adding an MLA method to your Book object that automatically formats the book for display. Display both APA and MLA formats for the book:[3]
        APA: Last, F. M. (Year) Title. City, State: Publisher.
        MLA: Last, First M. Title. Publisher, Year.
  4. Extend the program above, allowing the user to enter multiple book titles, one at a time. Add each book to an array of books. Display the full array in APA and MLA format after each object is added to the array.
  5. Extend the program above, allowing the user to choose either APA or MLA format, and display the selected format for each book. List the books in alphabetical order.

Lesson SummaryEdit

  • An object is a set of properties or methods.[4] Each object holds related data.[5]
  • Objects are written in the name:value pair format.[4] Each pair must be separated by a comma. [5]
  • Object properties may be accessed using the dot notation or the bracket notation. [6]
  • In JavaScript, almost everything is an object. Only primitive date types, such as number, string, and Boolean, are not objects.[7]

Key TermsEdit

method
An action that an object can perform.[8]
object
In JavaScript, almost "everything" is an object. Booleans, numbers, strings, dates, maths, regular expressions, arrays functions, and objects. All values, except primitive values, are objects.[9]
property
A property is a value associated with a JavaScript object.[10]
this
Refers to the owner of a function.[11]

See AlsoEdit

ReferencesEdit

Lesson 11 - DOM and BOMEdit

This lesson introduces the JavaScript Document Object Model (DOM) and Browser Object Model (BOM).


Objectives and SkillsEdit

Objectives and skills for this lesson include:[1]

  • Identify and construct the Document Object Model (DOM) tree
    • window; document; body; other HTML elements
  • Complete and debug code that outputs to an HTML document
    • innerHTML; document.write
  • Complete and debug code that interacts with the Browser Object Model (BOM)
    • Manage state; display dialogs; determine screen size

ReadingsEdit

  1. Wikipedia: Document Object Model
  2. Wikipedia: Browser Object Model
  3. Wikibooks: JavaScript/Introduction to the Document Object Model (DOM)

MultimediaEdit

  1. YouTube: JavaScript Tutorial for Beginners - 25 - Document Object Model
  2. YouTube: JavaScript Tutorial for Beginners - 40 - Traversing the DOM
  3. YouTube: JavaScript Tutorial for Beginners - 41 - Traversing the DOM Part 2
  4. YouTube: JavaScript Tutorial for Beginners - 42 - Traversing the DOM Part 3
  5. YouTube: JavaScript Tutorial for Beginners - 52 - Window object
  6. YouTube: An Introduction to the DOM (Document Object Model) in JavaScript
  7. YouTube: Document Object Model Tutorial
  8. Youtube: Javascript DOM Manipulation

ExamplesEdit

ActivitiesEdit

Complete the following activities using external JavaScript code. Apply JavaScript best practices, including comments, indentations, naming conventions, and constants. Use input elements for input and respond to input or change events, add buttons and respond to click events, or set a timer interval and respond to interval events. Use HTML elements for output. Use separate functions for each type of processing. Avoid global variables by passing parameters and returning results. Create test data to validate the accuracy of each program. Add comments at the top of the program and include references to any resources used.

  1. Create JavaScript code to display all tags in the current HTML document using document.getElementByTagName("*").
  2. Create JavaScript code to display the nodeName and nodeType for all nodes in the current HTML document using childNodes. Use a JavaScript object (key/value pairs) to look up the nodeType and convert the type number to a string description.
  3. Create JavaScript code to display the current window size, screen size, and location information. Use the resize event to update the display whenever the window size changes.

Lesson SummaryEdit

  • The Document Object Model (DOM) defines a standard for accessing documents.[2]
  • The Browser Object Model (BOM) allows JavaScript to "talk to" the browser.[3]
  • In the HTML DOM, the Element object represents an HTML element, like P, DIV, A, TABLE, or any other HTML element.[4]
  • Parent-child relationships within the DOM can be used to target document elements. It is possible to move (traverse) from parent to child (downwards), from child to parent (upwards), and from sibling to sibling (sideways).[5]
  • HTML DOM is a standard for how to get, change, add, or delete HTML elements.[6]

Key TermsEdit

Browser Object Model (BOM)
The API of the browser that allows JavaScript to communicate with the browser.[7]
Document Object Model (DOM)
The data representation of the objects that comprise the structure and content of a document on the web.[8]
node
An HTML element. The "DOM" is a tree structure that represents the HTML of the website, and every HTML element is a "node". More specifically, "Node" is an interface that is implemented by multiple objects.[source?]

See AlsoEdit

ReferencesEdit

Lesson 12 - Dynamic HTMLEdit

This lesson introduces dynamic HTML.


Objectives and SkillsEdit

Objectives and skills for this lesson include:[1]

  • Complete and debug code that locates, modifies, and adds HTML elements and attributes
    • getElementByld; getElementsByTagName; getElementsByClassName; setAttribute; createElement

ReadingsEdit

  1. Wikipedia: Dynamic HTML
  2. Wikibooks: JavaScript/DHTML

MultimediaEdit

  1. YouTube: JavaScript Tutorial for Beginners - 36 - Creating a new element
  2. YouTube: JavaScript Tutorial for Beginners - 37 - Creating a new element Part 2
  3. YouTube: JavaScript Tutorial for Beginners - 38 - Remove element
  4. YouTube: JavaScript Tutorial for Beginners - 39 - Create attribute
  5. YouTube: JavaScript Create HTML Element: How to dynamically add tags to your pages
  6. YouTube: JavaScript Changing CSS Styles
  7. YouTube: JavaScript Dynamic Welcoming Message

ExamplesEdit

ActivitiesEdit

Complete the following activities using external JavaScript code. Apply JavaScript best practices, including comments, indentations, naming conventions, and constants. Use input elements for input and respond to input or change events or add buttons and respond to click events. Use HTML elements for output. Use separate functions for each type of processing. Avoid global variables by passing parameters and returning results. Create test data to validate the accuracy of each program. Add comments at the top of the program and include references to any resources used.

  1. Extend any of the activities from JavaScript Programming/Arrays to use an array to hold the information generated during processing and display the results from the array using dynamic HTML to create and append HTML elements after processing is complete.

Lesson SummaryEdit

  • To dynamically change your HTML with JavaScript, you need to fully understand how to traverse the node tree and the relationship between nodes.[2]
  • Each HTML element node, except the root element node, has a parent node.[3]
  • Text is the value of the text node. The text node has to be created and appended to the element. [4]

Key TermsEdit

dynamic HTML
Dynamic HTML (DHTML) is based on properties of the HTML, JavaScript, CSS, and DOM which helps in making dynamic content. DHTML makes use of Dynamic object model to make changes in settings and also in properties and methods.[5]
node
Every Element in the HTML document is a node [6]
NodeList object
A NodeList object is a list (collection) of nodes extracted from a document.[7]
node relationships
The nodes in the node tree have a hierarchical relationship to each other. The terms parent, child, and sibling are used to describe the relationships. [8]

See AlsoEdit

ReferencesEdit

Lesson 13 - Forms and SecurityEdit

This lesson introduces JavaScript form processing and security.


Objectives and SkillsEdit

Objectives and skills for this lesson include:[1]

  • Complete and debug code that retrieves input from forms and sets form field values
    • Retrieve form values; identify the DOM path; get values from different types of elements; prepopulate values; mask values
  • Describe the form submission process
    • onsubmit; post versus get; potential targets for submission
  • Implement exception handling
    • try; catch; finally

ReadingsEdit

  1. Wikipedia: Form (HTML)
  2. Wikipedia: Data validation
  3. Wikipedia: Regular expression
  4. Wikibooks: JavaScript/Forms
  5. Wikipedia: Web application security
  6. Wikipedia: Exception handling

MultimediaEdit

  1. YouTube: JavaScript Form Validation
  2. YouTube: JavaScript Tutorial for Beginners - 43 - Form Validation Part 1
  3. YouTube: JavaScript Tutorial for Beginners - 44 - Form Validation Part 2
  4. YouTube: JavaScript Tutorial for Beginners - 45 - Form Validation Part 3
  5. YouTube: JavaScript Tutorial for Beginners - 46 - Form Validation Part 4
  6. YouTube: JavaScript Tutorial for Beginners - 47 - Form Validation Part 5
  7. YouTube: Writing Secure JavaScript

ExamplesEdit

ActivitiesEdit

Complete the following activities using external JavaScript code. Apply JavaScript best practices, including comments, indentations, naming conventions, and constants. Use input elements for input and respond to input or change events or add buttons and respond to click events. Use HTML elements for output. Use separate functions for each type of processing. Avoid global variables by passing parameters and returning results. Create test data to validate the accuracy of each program. Add comments at the top of the program and include references to any resources used.

  1. Create an HTML form that allows the user to enter their first name, last name, address, city, region, postal code, email address, phone number, and date of birth.
  2. Review W3Schools: HTML Form Attributes. Use form attributes wherever possible to improve data validity. Include required, min, max, minlength, maxlength, pattern, and/or type, where appropriate. Include a default value for region.
  3. Use JavaScript to validate data entry. Disable the Submit button by default, and only enable it when all data passes validation. Include appropriate error messages to inform the user of any necessary corrections. Help the user enter data matching appropriate patterns for phone number and date of birth based on your locale.
  4. Include two buttons, one labeled GET and the other labeled POST. Use JavaScript to change the form request method based on the button selected. Use https://postman-echo.com to echo submitted requests and compare the differences in data transmission format for the two types of requests.

Lesson SummaryEdit

  • Forms are an HTML element with some unique properties and events that allow programmers to inspect and control the form through JavaScript.[source?]

Key TermsEdit

checkValidity()
This input element method returns true if the element contains valid data according to the rules you have specified in the input field.[2]
Client-Side Form Validation
An initial check that happens in the browser and helps ensure users fill out the form using correct data formats. Error messages are displayed if corrections are needed.[3]
pattern
HTML <input> attribute that specifies a regular expression that the <input> element's value is checked against on form submission.[4]
reportValidity()
Runs the checkValidity method on the element's child controls. Those child elements which do not satisfy their validation constraints are reported to the user.[5]
required
HTML <input> attribute that when present, will specify that an input field must be filled out before submitting the form.[6]
Server-Side Form Validation
A validation that checks the data sent to the server and ensures that incorrect or malicious data is rejected.[3]
setCustomValidity()
This method sets the custom validity message for the selection element to the specified message. To reset the validity use an empty string as a parameter.[7]
validityState()
The ValidityState returns an object containing the errors detected via HTML constraint validation.[8]

See AlsoEdit

ReferencesEdit

Lesson 14 - AJAX and JSONEdit

This lesson introduces AJAX and JSON.


Objectives and SkillsEdit

Objectives and skills for this lesson include:

  • Send and receive JSON data using AJAX

ReadingsEdit

  1. Wikipedia: AJAX
  2. Wikipedia: JSON
  3. Wikibooks: JavaScript/XMLHttpRequest
  4. Wikibooks: JavaScript/Handling JSON

MultimediaEdit

  1. YouTube: JSON and AJAX Tutorial: With Real Examples
  2. YouTube: JSON Crash Course

ExamplesEdit

ActivitiesEdit

Complete the following activities using external JavaScript code. Apply JavaScript best practices, including comments, indentations, naming conventions, and constants. Use input elements for input and respond to input or change events or add buttons and respond to click events. Use HTML elements for output. Use separate functions for each type of processing. Avoid global variables by passing parameters and returning results. Create test data to validate the accuracy of each program. Add comments at the top of the program and include references to any resources used.

  1. Convert your JavaScript Programming/Forms and Security project to send form data using AJAX and JSON rather than through form submission. Use POST to add users and use GET to retrieve user data.
  2. Use an online API simulation tool such as jsonplaceholder.typicode.com to test your code. Depending on configuration of your API simulation tool, the returned data may or may not match the data you send. The intent is to test XMLHttpRequest communication rather than the API itself.
  3. Optional: See Node.js REST API for information and examples on how to set up your own test JavaScript web server.

Lesson SummaryEdit

Additional items will be contributed by course participants

Key TermsEdit

AJAX (Asynchronous JavaScript and XML)
With AJAX, web applications can send and retrieve data from a server asynchronously (in the background) without interfering with the display and behavior of the existing page.[1]
Data Interchange Format
A data-interchange format is a text format which is used to interchange or exchange data between different platforms and operating systems. JSON is the most popular and lightweight data-interchange format for web applications.[2]
GET
GET is used to request data from a specified resource. GET is one of the most common HTTP methods (and the default method).[3]
JSON
JSON is text, written using JavaScript object notation.[4]
onReadyStateChange
It is an event handler that is called whenever the readyState attribute changes.[5]
POST
POST is used to send data to a server to create/update a resource. The data sent to the server with POST is stored in the request body of the HTTP request.[6]
XMLHttpRequest
The XMLHttpRequest object is used to interact with the server (get or post data). This enables a Web page to update just part of a page without disrupting what the user is doing.[7]

See AlsoEdit

ReferencesEdit

Lesson 15 - Libraries and FrameworksEdit

This lesson introduces JavaScript libraries and frameworks.


Objectives and SkillsEdit

Objectives and skills for this lesson include:

  • Understand the advantages and disadvantages of using JavaScript libraries and frameworks
  • Recognize currently popular JavaScript libraries and frameworks

ReadingsEdit

  1. Wikipedia: JavaScript library
  2. Wikipedia: JavaScript framework
  3. Wikipedia: Comparison of JavaScript frameworks

MultimediaEdit

  1. YouTube: JavaScript Tutorial For Beginners #45 - JavaScript Libraries
  2. YouTube: Choosing Your JavaScript Framework

ExamplesEdit

ActivitiesEdit

  1. List advantages and disadvantages of using JavaScript libraries and frameworks.
  2. Research currently popular JavaScript libraries and frameworks. Consider different source approaches, including market share, industry recommendations, GitHub usage, and job search listings.

Lesson SummaryEdit

  • Bullet points

Key TermsEdit

term
definition

See AlsoEdit

ReferencesEdit

Lesson 16 - Node.js REST APIEdit

This lesson introduces Node.js, Express.js and REST APIs.


Objectives and SkillsEdit

Objectives and skills for this lesson include:

  • Understand Node.js concepts
  • Understand Express.js concepts
  • Use Node.js and Express.js to implement a simple REST API

ReadingsEdit

  1. Wikipedia: Node.js
  2. Wikipedia: Express.js
  3. Wikipedia: REST API

MultimediaEdit

ExamplesEdit

ActivitiesEdit

  1. Install Node.js
  2. Configure and test Express.js
    • Create a new folder for your REST server application. In that folder, run the following command to generate an Express.js template:
          npm install express-generator
    • Install Express and CORS using the following commands:
          npm install express --save
          npm install cors --save
    • Copy the Hello World example code to create a simple Express.js website.
    • Start the website using the command:
          node server.js
    • Test your server by using your web browser to navigate to:
          http://localhost:3000
  3. Create a simple REST API

Lesson SummaryEdit

  • Bullet points

Key TermsEdit

term
definition

See AlsoEdit

ReferencesEdit