JavaScript Programming/Collection

JavaScript Programming

edit


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.

Preparation

edit

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.

Lessons

edit
  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 Also

edit

Bibliography

edit

References

edit

Lesson 1 - Introduction

edit

This lesson introduces the JavaScript programming language and environments.


Objectives and Skills

edit

Objectives and skills for this lesson include:[1]

  • Apply JavaScript best practices
    • Comments; indentations (code formatting); 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

Readings

edit
  1. Wikibooks: JavaScript/Introduction
  2. Wikibooks: JavaScript/First program
  3. Wikibooks: JavaScript/Placing the code
  4. CodeCademy: File Paths

Multimedia

edit
  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 - Output
  5. YouTube: Beginner JavaScript Tutorial - 2 - Comments and Statements
  6. YouTube: JavaScript - How to use the console in a browser
  7. YouTube: noscript Tag - JavaScript Programming
  8. YouTube: Using Alert & Console.log in JavaScript
  9. YouTube: JavaScript for Beginners — Console Logging
  10. YouTube: Clean Code: Formatting and Comments
  11. YouTube: Javascript The innerHTML property
  12. YouTube: javascript: part1, console.log, getElementByID & innerHTML
  13. YouTube: JavaScript Loading Strategies (async and defer)
  14. Youtube: JavaScript DOM Tutorial #4 - The Query Selector
  15. Youtube: The innerText vs. textContent properties in JavaScript

Examples

edit

To test the following examples, copy the code and paste it in the body of an HTML file and view the file in a browser, or use a JavaScript test environment such as W3Schools: Tryit Editor.

document.write()

edit

document.write() writes a string of text to a document stream.

<script>
  document.write("Hello World");
</script>

window.alert()

edit

window.alert() displays an alert box with an optional message and an OK button.

<script>
  document.alert("Hello World");
</script>

innerHTML and InnerText

edit

The innerHTML and innerText returns or sets the inner HTML and text of an element, respectively.

<p id="id-name"> This text will be replaced</p>

<script>
  document.getElementById("id-name").innerHTML = "Hello World";
</script>

console.log()

edit

The window.alert() outputs a message or a value to the console.

<script>
  console.log("Hello World")
</script>

Activities

edit
  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() (which is the same as alert()). window.alert() is best practice.
    • Use document.getElementById().innerText or document.getElementById().innerHTML to change the text of a paragraph
    • 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()
      • <script src="..."> is how you link to an external JavaScript page, the name of which should end in .js, and should have a closing </script> tag
  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 Summary

edit
  • 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 defer 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 HTML Element 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 Terms

edit
Console
Is an object which provides access to the browser debugging console. The console object provides us with several different methods, like :log(), error(), warn(), clear(),time(), etc. To open the developer console window for Chrome, use the keyboard shortcut Ctrl - Shift - J on Windows or Cmd + Option + J on a Mac. To open it for Firefox, use the shortcut Ctrl + Shift + K on Windows, or Cmd + Option + K on a Mac.[23]
JavaScript
The proprietary name of a high-level, object-oriented scripting language used especially to create interactive applications running over the internet.[24]
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.[25]
ECMAScript
A scripting-language specification, standardized by Ecma International, which was created to standardize JavaScript and foster multiple independent implementations.[26]
external script
A script file that is attached to the HTML using the <script> element. Example - <script src='myscript.js'>.[source?]
Nonscript Tag
The <noscript> tag defines an alternate content to be displayed to users that have disabled scripts in their browser or have a browser that doesn't support script. The <noscript> element can be used in both <head> and <body>. [27]
statement
A command that performs an action. An example being, alert("string"), where alert prints the string within the parenthesis.[source?]

Review Questions

edit
  • What are three different ways to implement JavaScript into an HTML file?
  • Is it mandatory to end a statement with a semicolon in JavaScript?
  • What can you do with document.getElementById() in JavaScript?
  • How do you create a windowed message with JavaScript?
  • What is a common use for comments during code testing?
  • How do you embed JavaScript code in an HTML file?
  • What is <noscript> used for?
  • Why is linking to external scripts considered the best practice for script placement?
  • Where is the best place to put <script></script> for faster loading webpages?
  • What is the difference between defer and async?

See Also

edit

References

edit
  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. {{Cite web|url= https://www.geeksforgeeks.org/console-in-javascript/#:~:text=In%20javascript%2C%20the%20console%20is,error()
  24. "Definition of JavaScript | Dictionary.com". www.dictionary.com. Retrieved 2021-01-22.
  25. "JavaScript Comments". www.w3schools.com. Retrieved 2020-08-26.
  26. Wikipedia: EMCAScript
  27. {{Cite web|url= https://developer.mozilla.org/en-US/docs/Web/HTML/Element/noscript

Lesson 2 - Variables and Expressions

edit

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


Objectives and Skills

edit

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.

Readings

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

Multimedia

edit
  • Variables
  1. YouTube: JavaScript Tutorial for Beginners - 03 - Variables
  2. YouTube: JavaScript Tutorial for Beginners - 04 - Variables Part 2
  3. YouTube: JavaScript Programming Tutorial 6 - Variables and Expressions
  4. YouTube: JavaScript Let, Const & Var
  5. YouTube: 7: How to Create Variables in JavaScript | JavaScript Tutorial | Learn JavaScript
  6. YouTube: What is a Variable? | JavaScript in less-than 3 minutes
  7. YouTube: Variables & Data Types | Javascript | Tutorial 6
  • Data Types and Operators
  1. YouTube: Javascript Variables & Data Types
  2. YouTube: JavaScript Tutorial for Beginners - 08 - Operators
  3. YouTube: A Basic Calculator
  4. YouTube: 20 String Methods in 7 Minutes
  • Input
  1. YouTube: Getting User Input | Javascript | Tutorial 9
  2. YouTube: How to accept JavaScript USER INPUT in 5 minute
  • Debugging
  1. YouTube: Debugging JavaScript (Google Chrome and Visual Studio Code)
  2. YouTube: Firefox JavaScript Debugger
  3. YouTube: Debugging JavaScript - Chrome DevTools 101
  • Type Coercion
  1. YouTube: JavaScript Type Coercion - Javascript Tutorial #4
  2. JavaScript & Type Coercion
  • Expressions vs. Statements
  1. Expressions vs. Statements in JS / Intro to JavaScript ES6 programming, lesson 14

Examples

edit

Activities

edit

Complete two of 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.

Arithmetic

edit
  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 and MathsIsFun: Metric-US/Imperial Conversions. 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 Types

edit
  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.

Debugging

edit
  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 Summary

edit
  • By convention, JavaScript variable names are written in camelCase.[4]
  • In JavaScript, I explored variable declarations with let and const, string properties and methods such as length and toUpperCase(), primitive data types like number, string, boolean, null, and undefined, and various operators for string concatenation, arithmetic, assignment, increments, comparisons, and logical evaluations.
  • JavaScript Class, interface, record, and typedef names are often written in Title Case.[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]
  • Comments, which are annotations or explanations of written code[7], are done in JavaScript using // for a single line, and /* ... */ for multiple lines.
  • JavaScript has 7 data types: Number, String, Boolean, Null, Undefined, Function, and Object. Null and Undefined data types can't contain values.[8]
  • There are 6 types of objects in JavaScriptː Object, Date, Array, String, Number and Boolean.[8]
  • JavaScript has only 1 type of number.[9]
  • With some other languages, like Java and C, there is a special “character” type. JavaScript consists of only one type, string.[10]
  • The typeof operator is used to find the data type of the variable.[8]
  • JavaScript has built-in functions to work with strings and numbers[11]
  • 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.[8] Quotation marks used inside can match the outside ones only if they are preceded by the backslash escape character.[12]
  • You can convert between data types in JavaScript.[8]
  • "use strict" is a literal expression that requires / enforces variable declaration. It allows for cleaner code to be written.[13]

Key Terms

edit
array
An array is a type of variable that stores a collection of values. The position of each value inside the array is that value's index. Indexes in JavaScript always start at 0.[14]
assignment
Assigning a value to a variable or constant with the "=" operator.[source?]
Boolean
Data type which has only two values, True and False.[15]
camel case
Method of joining multiple words into one variable name where the first word is not capitalized and every subsequent first letter of following words are capitalized[16]
Title case or pascal case
Method of joining multiple words into one variable name where the first letter of every word is capitalized.[16]
concatenation
Method of joining two strings, data, or other text together in programming. In JavaScript, strings are concatenated using the '+' operator. [17]
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.
constant
A keyword introduced from ES2015, It is a container for storing a permanent data value that cannot be changed later in the program.[18]
Equality
An operator referencing when two values are equal, "==", this is distinct from the assignment ("=") operator referenced above.[18]
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 [19]
null
A special value which represents "nothing." It is not a reference to a null pointer.[15]
number
Data type in JavaScript which represents both integers and floating-point value.[15]
object
A variable that can contain many values.[20]
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.[21]

scope

The current context of the code, refers to the accessibility of functions and variables.

string
Can consist of one character or many. A string must be surrounded by quotation marks.[15]
type coercion
The automatic or implicit conversion of values from one data type to another (such as strings to numbers).[22]
undefined
A variable which has not been assigned a value. If a variable is simply declared, but not assigned anything, it becomes undefined.[15]
variable
A container for storing a data values. Variables are used to hold values in expressions. [6]

See Also

edit

References

edit

Lesson 3 - Functions

edit

This lesson introduces JavaScript functions.


Objectives and Skills

edit

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

Readings

edit
  1. Wikibooks: JavaScript/Functions
  2. Wikibooks: JavaScript/Anonymous functions
  3. Mozilla: JavaScript/Functions
  4. JavaScript Functions

Multimedia

edit
  1. YouTube: JavaScript Functions
  2. YouTube: JavaScript Tutorial for Beginners - 06 - Functions
  3. YouTube: JavaScript Tutorial for Beginners - 07 - Functions Part 2
  4. YouTube: JavaScript Tutorial for Beginners - 14 - Return statement
  5. YouTube: JavaScript Tutorial for Beginners - 15 - Global and local variables
  6. YouTube: JavaScript Tutorial for Beginners - 16 - Pass by value
  7. YouTube: Passing by reference vs. by value - JavaScript Tutorial
  8. YouTube: JavaScript Functions & Parameters
  9. YouTube: Number Methods and Math Objects in JavaScript
  10. YouTube: How to Create JavaScript Functions
  11. YouTube: Functions and Return
  12. How To Create/Use Functions - JavaScript Essentials

Examples

edit

Activities

edit

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. 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 and Metric - US/Imperial Conversion Charts. 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.[2]
  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, use the Math.ceil function. Calculate the total cost of the paint as: gallons * price per gallon.[3]

Lesson Summary

edit
  • A JavaScript function is a block of code designed to perform a particular task.[4]
  • Indent JavaScript code blocks (functions, conditions, loops, comment blocks, etc.) 2 spaces for each indent level.[5]
  • Functions break down code into reusable blocks of code each of which performs a specific task.[6]
  • Code inside a function is not executed at the time of declaration. A function has to be called upon (invoked) first.[7]
  • JavaScript function expressions can invoke themselves.[8]
  • JavaScript functions do not check the number of arguments received. Missing arguments are set to undefined.[9]
  • JavaScript functions do not check the data type of passed arguments.[9]
  • JavaScript functions can only return one value.[10]
  • A key benefit to using functions is that breaking. program down into smaller, simpler tasks makes it more manageable and maintainable.[11]
  • Functions can be used as values.[12]

Key Terms

edit
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.[13]
argument
The real value passed to (and received by) the function.[14]
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.[15]
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.[16]
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.[17]
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.[18]
global variable
A variable declared outside a function.[19]
invocation
The code inside the function will execute when "something" invokes (calls) the function.[20]
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.[21]
parameter
A name listed in a function definition.[22]
return
Ends function execution and returns a value in the place the function was invoked.[23]
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).[24]
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.[25]

See Also

edit

References

edit

Lesson 4 - Events

edit

This lesson introduces JavaScript events.


Objectives and Skills

edit

Objectives and skills for this lesson include:[1]

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

Readings

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

Multimedia

edit
  1. YouTube: What are JavaScript Events?
  2. YouTube: JavaScript Tutorial for Beginners - 33 - Intro to events
  3. YouTube: JavaScript 2021 Tutorial 9 - Calling functions from events
  4. YouTube: JavaScript Tutorial for Beginners - 32 - Changing an image
  5. YouTube: JavaScript Tutorial for Beginners - 34 - The mouseover event
  6. YouTube: addEventListener() - Beau teaches JavaScript
  7. YouTube: JavaScript Questions: What is Event Delegation, Event Propagation, Event Bubbling?
  8. YouTube: A Complete Overview of JavaScript Events - All You Need To Know
  9. Simplilearn: Understand JavaScript Events with Examples

Examples

edit

Activities

edit

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, use the Math.ceil function. Calculate the total cost of the paint as: gallons * price per gallon.[4]

Lesson Summary

edit
  • 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]
  • Data on events can include not only the type of event, but when it occurred and what caused it to occur. [12]

Key Terms

edit
DOM (Document Object Model)
The HTML DOM model is constructed as a tree of objects. The DOM defines a standard for accessing documents.[13]
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.[14]
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"[15]
event listener
It is attached to an element and fires a function when the event is detected on the element. [16]
onchange
An HTML element has been changed such as a user changing an input field value. (Sometimes still have to hit enter on keyboard to trigger.)[17]
onclick
An HTML event when the user clicks an HTML element.[18]
onkeydown
An HTML event when the user pushes a keyboard key.[19]
onload
The browser has finished loading the page.[19]
onmouseout
The user moves the mouse away from an HTML element.[17]
onmouseover
An HTML event when the user moves the mouse over an HTML element.[17]
Touch Event
A set of HTML events that occur when a user touches a touch-based device.[17]

See Also

edit

References

edit

Lesson 5 - Conditions

edit

This lesson introduces JavaScript conditions.


Objectives and Skills

edit

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)

Readings

edit
  1. Wikipedia: Structured programming
  2. Wikipedia: Conditional (computer programming)
  3. Wikibooks: JavaScript/Control structures
  4. Mozilla: if...else

Multimedia

edit
  1. YouTube: How to Create Conditions in JavaScript | Conditional Statements | JavaScript Tutorial
  2. YouTube: Introduction to Conditional Statements - p5.js Tutorial
  3. YouTube: JavaScript if - else Statement
  4. YouTube: How to use if/else conditions in JavaScript
  5. YouTube: JavaScript Tutorial for Beginners - 13 - Function and if statement
  6. YouTube: JavaScript Tutorial - Switch Statement
  7. YouTube: Switch - How to Use the JavaScript Switch Statement
  8. If Else Conditional Statements & Switch In JavaScript | JavaScript Tutorial For Beginners

Examples

edit

Activities

edit

Complete one of the following activities for each type of condition 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 Conditions

edit
  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 Conditions

edit
  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 Validation

edit
  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 Summary

edit
  • 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]
  • Switch cases use strict comparison (===). The values must be of the same type to match.[10]
  • Switch statements are better to use over If/Else statements when you are aware of the exact data that can be input.[source?]
  • 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.[11]
  • The switch statement may have an optional default case. It specifies the block of code that runs if there is no case match.[12]
  • Conditional statements can be inside of other conditional statements, and can have multiple conditions to test.[13]
  • When writing conditions based on equality, "==" is used rather than "=", which is the assignment operator.[source?]

Key Terms

edit
boolean
A datatype that can only hold a value of either TRUE or FALSE.[14]
break
Keyword that breaks out of the switch block. This will stop the execution of inside the block.[15]
comparison operators
Comparison operators are used in logical statements to determine equality or difference between variables or values.[16]
conditional statement
It is a condition that has to be fulfilled (true) to perform an action.[17]
default
Keyword that specifies the code to run if there is no case match.[18]
"else" statement
The else statement is to specify a block of code to be executed if the same condition is false.[19]
"else if" statement
The else if statement specifies a new condition if the first condition is not met.[20]
"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.[21]
logical operators
Logical operators are used to determine the logic between variables or values.[22]
nested if statement
An if statement inside another if statement (multiple if statements).[23]
switch
Used to select one of many code blocks to be executed based on evaluation of a single expression.[24]

See Also

edit

References

edit

Lesson 6 - While Loops

edit

This lesson introduces JavaScript while and do while loops.


Objectives and Skills

edit

Objectives and skills for this lesson include:[1]

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

Readings

edit
  1. Wikipedia: Control flow
  2. Wikibooks: JavaScript/Control structures
  3. Techdifferences: Difference Between while and do-while Loop

Multimedia

edit
  1. YouTube: While/do while loop | JavaScript Full Tutorial
  2. YouTube: JavaScript Tutorial for Beginners - 11 - Loops
  3. YouTube: #16 While loop in JavaScript
  4. YouTube: freeCodeCamp.org While / Do While
  5. YouTube: JavaScript Tutorial For Beginners #16 - While Loops
  6. YouTube: JavaScript beginner tutorial 21 - do while loop
  7. YouTube: JavaScript Loops
  8. YouTube: 4.1: while and for Loops

Examples

edit

Activities

edit

Complete one the following activities in each category of loop 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 Loops

edit

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. (This might be helpful: Get Number from Prompt Input)
  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. Use hidden elements to keep track of the total and count.

Do While Loops

edit

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. Use hidden elements to keep track of the total and count.
  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 Summary

edit
  • 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; but can present performance issues in larger applications.[source?]
  • A "for" loop is set to run a set number of times or until a certain condition is met.
  • A "while" loop is set to run as long as a certain expression evaluates to true.
  • In a while loop, the condition is checked before any statement in the loop is executed, where as a do while loop will execute the statements once before checking the condition. [7]

Key Terms

edit
Increment
The increment operator (++) increments (adds one to) its operand and returns a value.[8]
Decrement
the Decrement operator (--) decrements (subtracts one from) its operand and returns a value.[9]
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.[10]
Infinite loop
A loop that theoretically runs forever.[11]
Iteration
It's a repetition of code or cycle, performed by a loop[12]
while loop
The while loop executes a block of code repeatedly as long as a specified condition is true.[13]

See Also

edit

References

edit

Lesson 7 - For Loops

edit

This lesson introduces JavaScript for loops and nested loops.


Objectives and Skills

edit

Objectives and skills for this lesson include:[1]

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

Readings

edit
  1. Wikipedia: Control flow
  2. Wikipedia: For loop

Multimedia

edit
  1. YouTube: JavaScript Tutorial for Beginners - 28 - getElementsByTagName Part 2
  2. Youtube: For Loops | Javascript | Tutorial 23
  3. YouTube: #17 For Loop in JavaScript
  4. YouTube: For Loops - Beau teaches JavaScript
  5. YouTube: JavaScript Tutorial for Beginners - 12 - Loops Part 2
  6. YouTube: JavaScript Tutorials for Beginners - 9 - How to Code Nested For Loops with JavaScript
  7. Youtube: JavaScript Nested Loops
  8. YouTube: #18 While vs For Loop | Which to use and When?
  9. JavaScript Loops

Examples

edit

Activities

edit

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 Loops

edit

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 Loops

edit

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 Summary

edit
  • 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.[10]
  • Continue only skips one iteration in the loop, where as break statements leave the loop completely.[source?]

Key Terms

edit
break
A statement used to jump out of a loop.[11]
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.[12]
for loop
Loops repeatedly executes a block of code a specified number of times.[13]
for/in loop
loops through the properties of an object.[13]
for/of loop
loops through the values of an iterable data structures such as Arrays, Strings, Maps, NodeLists, and more.[13]
loop counter
A variable that controls how many iterations of a loop occurs. [14]
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.[15]

See Also

edit

References

edit

Lesson 8 - Arrays

edit

This lesson introduces JavaScript arrays.


Objectives and Skills

edit

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;

Readings

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

Multimedia

edit
  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
  7. YouTube: 7.2: Arrays and Loops - p5.js Tutorial

Examples

edit

Activities

edit

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 Summary

edit
  • 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. [2]
  • Arrays are commonly used to loop across a set of elements.
  • In JavaScript, an array is not actually an explicit data type, but a predefined object of elements. [3]

Key Terms

edit
array
Arrays allow us to store multiple values in a single variable.[4]
array methods
Built-in functions to work with arrays in JavaScript.[5]
index or subscript
An integer that defines an element position within an array and is used to access that element.[2]
indexOf() method
The indexOf() method searches the array for the specified item, and returns its position (index). [6]
length
The number of elements in an array.[7] The length value is accessed by arrayName.length. [8]
multi-dimensional array
An array whose elements consist of other arrays.[9]
pop() method
This method removes the last element from an array.[10]
push() method
Is the easiest way to add a new element to an array.[2]
array.reduce() method
Runs a function on each array element to produce (reduce it to) a single value.[11]
sort() method
The sort() method sorts an array alphabetically. [12]
filter() method
The filter() method allows you to exclude array elements that match specific criterias. [13]

See Also

edit

References

edit

Lesson 9 - Date and Time

edit

This lesson introduces JavaScript objects using dates.


Objectives and Skills

edit

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

Readings

edit
  1. Wikibooks: JavaScript/Dates

Multimedia

edit
  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
  5. YouTube: JavaScript Programming Tutorial 48 - Using Dates and Unix Timestamps in JavaScript
  6. #16 How to use the JS Date object | JavaScript Full Tutorial

Examples

edit

Activities

edit

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 Summary

edit
  • 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 information 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]
  • The "date" input type creates a drop-down in html.
  • The timing events setTimeout() executes once and setInterval() executes function continously can be used to execute code at time interval.[6]
  • A UNIX epoch time and JavaScript date are not the same. Unix epoch time is seconds Ince the Unix Epoch, whereas the JavaScript date is milliseconds. [7]

Key Terms

edit
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.[8]
ISO
ISO is the International standard for the representation of dates and times. The ISO syntax is YYYY-MM-DD, and is the preferred JavaScript date format.[9]
new date()
Returns a new Date object that represents the current date and time.[10]
prototype
Allows you to add properties and methods to an object.[11]
setInterval()
A method calls a function or evaluates an expression at specified intervals (in milliseconds).[12]
setTimeout()
A method calls a function or evaluates an expression after a specified number of milliseconds.[13]
UTC
The Universal Coordinated Time (UTC) is the time set by the World Time Standard.[14]

See Also

edit

References

edit

Lesson 10 - Objects

edit

This lesson introduces JavaScript objects.


Objectives and Skills

edit

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

Readings

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

Multimedia

edit
  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: JavaScript this Keyword
  8. Javascript Objects Explained | Javascript Objects Tutorial

Examples

edit

Activities

edit

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 Summary

edit
  • 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]
  • Object properties can be a wide array of data types, such as arrays or even other objects.
  • In JavaScript, almost everything is an object. Only primitive date types, such as number, string, and Boolean, are not objects.[7]

Key Terms

edit
method
An action that an object can perform. A method is a function stored as a property, specific to that object. [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]

constructor

A constructor is a function that creates an object using the given inputs.

this
Refers to the owner of a function.[11]

See Also

edit

References

edit

Lesson 11 - DOM and BOM

edit

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


Objectives and Skills

edit

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

Readings

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

Multimedia

edit
  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: An Introduction to the DOM (Document Object Model) in JavaScript
  6. YouTube: Document Object Model Tutorial
  7. Youtube: Javascript DOM Manipulation
  8. YouTube: JavaScript Programming Tutorial 91 - Intro to the DOM
  9. JavaScript DOM Manipulation – Full Course for Beginners

Examples

edit

Activities

edit

elizabethannchazarretaarias/ssn0730/dob;6/14/1967/ recovery /over all fraud takan over all my profile under user made by dav/ and vijay/ stop and finde in all profile users/found at 3917 melliit ave ft.worth tx/and outher places under apple smart sofewere stolan alter and made payouts under apple and smart devices//and androuids/p;aces only to put a bug under my name and all recovery of stolan info made by contacts ir others ways smart devices aplace set to steal money over my complance lawsuites used only to larrer li8ve me a lone home less and without anyone ever bing truth i hope all fell better now ihave nowere to live or go/what hate over every hatefull person who whant this man who can have him and can live me alone ive never seen so much upseth with him and hate overme guess what all made under eval julicole and meditmolena and dallas hope oneday all can fell what i had to go thourgth in made me suffer killoff my family take awy` eeverty think i love neday may god be your judagedmebt and if you see /for icant keep bing around so much hatefull/ live me alone ihad to see only all in make me look like idont matter this provan evryday i get it now with same statemwent live me aloneomplete 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.getElementsByTagName("*").
  2. Create JavaScript code to display the nodeName and nodeType for all nodes in the current HTML document using the childNodes function. 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 Summary

edit
  • 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]
  • DOM is frequently depicted similarly to a tree, where the child nodes branch downwards off their parents.
  • 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]
  • DOM is essential for allowing webpages to change shape in response to user activity.
  • The BOM allows JavaScript to access several peices of information about a browser (with some limits for security) including: history, screen size, location, and cookies. [7]

Key Terms

edit
Browser Object Model (BOM)
The API of the browser that allows JavaScript to communicate with the browser.[8]
Document Object Model (DOM)
The data representation of the objects that comprise the structure and content of a document on the web.[9]
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.[10]
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.[11]

See Also

edit

References

edit

Lesson 12 - Dynamic HTML

edit

This lesson introduces dynamic HTML.


Objectives and Skills

edit

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
    • createElement, createTextNode, appendChild

Readings

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

Multimedia

edit
  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 Dynamic Welcoming Message
  7. YouTube: JavaScript Programming Tutorial 99 - Dynamically Adding Nodes

Examples

edit

Activities

edit

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 Summary

edit
  • 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]
  • Things DHTML is used for includes animating content, roll-over and dropdown menus, and verifying and responding to forms without using the server. [5]
  • To add a new element to the HTML DOM, you must create the element (element node) first, and then append it to an existing element.[4]
  • Creating strings and consectively adding HTML elements to them is a a common method of creating new elements to HTML using javascript.

Key Terms

edit
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.[6]
node
Every Element in the HTML document is a node [7]
NodeList object
A NodeList object is a list (collection) of nodes extracted from a document.[8]
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. [9]

See Also

edit

References

edit

Lesson 13 - Forms and Security

edit

This lesson introduces JavaScript form processing and security.


Objectives and Skills

edit

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

Readings

edit
  1. Wikipedia: Form (HTML)
  2. Wikipedia: Data validation
  3. Wikibooks: JavaScript/Forms
  4. Wikipedia: Web application security
  5. Wikipedia: Exception handling
  6. Input tag Definition and Usage

Multimedia

edit
  1. Youtube: The "submit" event on forms in JavaScript
  2. YouTube: JavaScript Form Validation
  3. YouTube: JavaScript Tutorial for Beginners - 43 - Form Validation Part 1
  4. YouTube: JavaScript Tutorial for Beginners - 44 - Form Validation Part 2
  5. YouTube: JavaScript Tutorial for Beginners - 45 - Form Validation Part 3
  6. YouTube: JavaScript Tutorial for Beginners - 46 - Form Validation Part 4
  7. YouTube: JavaScript Tutorial for Beginners - 47 - Form Validation Part 5
  8. YouTube: Learn Regular Expressions In 20 Minutes
  9. YouTube: Writing Secure JavaScript
  10. JavaScript Form Validation
  11. Youtube: Creating Contact Page with JS

Examples

edit
  1. w.youtu
  1. be.com/watch?v=30VeUWxZjS8

Activities

edit

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 Summary

edit
  • Forms are an HTML element with some unique properties and events that allow programmers to inspect and control the form through JavaScript.[source?]
  • A web form, also called an HTML form, is an online page that allows for user input. It is an interactive page that mimics a paper document or form, where users fill out particular fields. Typically, a web form contains a combination of form elements such as a checkbox, submit button, text box, etc. For added interactivity, web designers may use elements or classes such as "input" along with "action" and "method" attributes. [https://www.techopedia.com/definition/25561/web-form]

Key Terms

edit
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]
GET Method
Used to request data from a specified resource. The query string (name/value pairs) is sent in the URL of a GET request.[4]
pattern
HTML <input> attribute that specifies a regular expression that the <input> element's value is checked against on form submission.[5]
POST Method
Used to send data to a server to create/update a resource. The data sent to the server is stored in the request body of the HTTP request.[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.[6]
required
HTML <input> attribute that when present, will specify that an input field must be filled out before submitting the form.[7]
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.[8]
validityState()
The ValidityState returns an object containing the errors detected via HTML constraint validation.[9]

See Also

edit

References

edit

Lesson 14 - AJAX and JSON

edit

This lesson introduces AJAX and JSON.


Objectives and Skills

edit

Objectives and skills for this lesson include:

  • Send and receive JSON data using AJAX

Readings

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

Multimedia

edit
  1. YouTube: JSON and AJAX Tutorial: With Real Examples
  2. YouTube: JSON Crash Course
  3. YouTube: Learn JSON - Full Crash Course for Beginners
  4. AJAX - Beau teaches JavaScript

Examples

edit

Activities

edit

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 Summary

edit

Additional items will be contributed by course participants

  • JavaScript Object Notation or JSON is a universal data structure used to exchange information between multiple engines, languages, and servers. [1]
  • JSON is a large string that stores literals, and has its own formatting and syntax.
  • AJAX, or Asynchronous Javascript and XML, is a method for javascript to communicate with external webpages and/or servers.
  • Using AJAX allows web developers to update their webpages without having to refresh or redirect the user to another page.
  • GET and POST are the 2 main methods, being used to request and send data to servers, respectively.

Key Terms

edit
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.[2]
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.[3]
GET
GET is used to request data from a specified resource. GET is one of the most common HTTP methods (and the default method).[4]
JSON
JSON is text, written using JavaScript object notation.[5]
onReadyStateChange
It is an event handler that is called whenever the readyState attribute changes.[6]
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.[7]
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.[8]

See Also

edit

References

edit

Lesson 15 - Libraries and Frameworks

edit

This lesson introduces JavaScript libraries and frameworks.


Objectives and Skills

edit

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

Readings

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

Multimedia

edit
  1. YouTube: JavaScript Tutorial For Beginners #45 - JavaScript Libraries
  2. YouTube: What is a JavaScript Framework?
  3. YouTube: Choosing Your JavaScript Framework
  4. What is the difference between a framework and a library?

Examples

edit

Activities

edit
  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 Summary

edit
  • Web frameworks provide a standard way to build and deploy web applications on the World Wide Web.[1]
  • A library provides a set of helper functions/objects/modules which your application code calls for specific functionality.[2]

Key Terms

edit
term
definition
Library
Collection of functions that are used to reuse and simplify coding.[3]
Framework
A web application framework is a software framework that is designed to support the development of dynamic websites, Web applications and Web services. The framework aims to alleviate the overhead associated with common activities used in Web development. For example, many frameworks provide libraries for database access, templating frameworks and session management, and often promote code reuse.[1]

See Also

edit

References

edit

Lesson 16 - Node.js REST API

edit

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


Objectives and Skills

edit

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

Readings

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

Multimedia

edit

Examples

edit

Activities

edit
  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 Summary

edit
  • Bullet points

Key Terms

edit
term
definition

See Also

edit

References

edit