GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Main Page
  • Browse
  • Recent changes
  • Guided tours
  • Random
  • Help
  • Portal
  • Colloquium
  • News
  • Projects
  • Sandbox
  • Search
  • Donate
  • Create account

This view

  • Original page
  • New address

GeezerVison is showing en.wikiversity.org — JavaScript Programming/Collection - Wikiversity

< JavaScript Programming

JavaScript Programming


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

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

  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

  • Computer Programming
  • JavaScript
  • Exam 98-382: Introduction to Programming Using JavaScript
  • Wikipedia: JavaScript
  • DoFactory: JavaScript Tutorial
  • JavaScript.Info
  • Stackify: JavaScript Tutorials
  • Microsoft: Web Development for Beginners
  • Mozilla: JavaScript Tutorials
  • Grasshopper App

Bibliography

  • Wikibooks: JavaScript
  • Eloquent JavaScript: A Modern Introduction to Programming
  • https://javascript.info/

References

  1. ↑ Wikipedia: JavaScript
  2. ↑ Wikipedia: JavaScript

Lesson 1 - Introduction

This lesson introduces the JavaScript programming language and environments.


Objectives and Skills

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

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

Multimedia

  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

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()

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

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

window.alert()

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

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

innerHTML and InnerText

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()

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

<script>
  console.log("Hello World")
</script>
  • W3Schools: JavaScript Introduction
  • W3Schools: JavaScript Comments
  • W3Schools: JavaScript Output
  • W3Schools: JavaScript Where To
  • W3Schools: HTML noscript tag
  • W3Schools: Difference between innerText and innerHTML
  • W3Schools: Window Alert()
  • W3Schools: DOM write() Method
  • W3Schools: GetElementById()
  • W3Schools: HTML DOM Element innerHTML
  • Example Code

Activities

  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

  • 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

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

Review Questions

  • 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?
  • What is the purpose of the <script> tag in an HTML document?

See Also

  • Wikipedia: JavaScript
  • Wikipedia: Input/output
  • Grasshopper: JavaScript Coding App for Beginners
  • Google: JavaScript Style Guide
  • Google: Get Started with the PageSpeed Insights API
  • JavaScript Info: Scripts: async, defer
  • Codecademy: Introduction to Javascript
  • Javascript Learning Resource
  • The Modern Javascript Tutorial
  • Learn Javascript Online
  • Geeks for Geeks: Understanding basic JavaScript codes
  • W3Schools: JavaScript
  • Async Vs Defer - JavaScript Loading Explanation

References

  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

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


Objectives and Skills

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

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

Multimedia

  • 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

  • W3Schools: JavaScript Syntax
  • W3Schools: JavaScript Variables
  • W3Schools: JavaScript Operators
  • W3Schools: JavaScript Statements
  • W3Schools: JavaScript Arithmetic
  • W3Schools: JavaScript Assignment
  • W3Schools: JavaScript Popup Boxes
  • Freecodecamp: JavaScript Popup Boxes with Examples
  • W3Schools: JavaScript Debugging
  • W3Schools: JavaScript Data Types
  • W3Schools: JavaScript Numbers
  • W3Schools: JavaScript Number Methods
  • W3Schools: JavaScript Strings
  • W3Schools: JavaScript String Methods
  • W3Schools: JavaScript Strict Mode
  • W3Schools: JavaScript Type Conversion
  • W3Schools: Null vs Undefined
  • JavaScript — Null vs. Undefined
  • Example Code
  • MDN Web Docs: Expressions and Operators
  • GeeksforGeeks: Javascript Expressions
  • Data types: Data Types in JavaScript

Activities

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

  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

  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

  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

  • 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 JavaScript, 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

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.
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. (Ex. CamelCase)[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

  • Wikipedia: Variable (computer science)
  • Wikipedia: Constant (computer programming)
  • Wikipedia: Data type
  • Wikipedia: Expression (computer science)
  • Wikipedia: Statement (computer science)
  • Wikipedia: Assignment (computer science)
  • Wikipedia: Order of operations
  • Wikipedia: Self-documenting code
  • Robin Wieruch: Javascript Naming Convention
  • Var, Let, and Const – What's the Difference?
  • The typeof Operator
  • Get Started with Debugging JavaScript in Chrome DevTools

References

  1. ↑ Microsoft: Exam 98-382 Introduction to Programming Using JavaScript
  2. ↑ PythonLearn: Variables, expressions, and statements
  3. ↑ Wikibooks: Programming Fundamentals/Practice: Data and Operators
  4. ↑ 4.0 4.1 https://google.github.io/styleguide/jsguide.html
  5. ↑ https://google.github.io/styleguide/jsguide.html
  6. ↑ 6.0 6.1 6.2 6.3 6.4 W3Schoolsː JavaScript Variables
  7. ↑ "Comment (computer programming)". Wikipedia. 2021-01-08. https://en.wikipedia.org/w/index.php?title=Comment_(computer_programming)&oldid=999054165. 
  8. ↑ 8.0 8.1 8.2 8.3 8.4 W3Schoolsː JavaScript Data Types
  9. ↑ W3Schoolsː JavaScript Numbers
  10. ↑ "Data types". javascript.info. Retrieved 2019-09-05.
  11. ↑ MDN Web Docs: Data Types and Data Structures
  12. ↑ W3Schoolsː JavaScript Strings
  13. ↑ W3Schoolsː JavaScript Use Strict
  14. ↑ "JavaScript Arrays". www.w3schools.com. Retrieved 2024-03-08.
  15. ↑ 15.0 15.1 15.2 15.3 15.4 JavaScript.Infoː Data Types
  16. ↑ 16.0 16.1 Microsoft: Capitalization Styles
  17. ↑ "What is Concatenate?". www.computerhope.com. Retrieved 2020-09-04.
  18. ↑ 18.0 18.1 W3Schools: JavaScript const
  19. ↑ "JavaScript Let". www.w3schools.com. Retrieved 2020-09-01.
  20. ↑ W3Schoolsː JavaScript Objects
  21. ↑ "Programming Fundamentals/Order of Operations - Wikibooks, open books for an open world". en.wikibooks.org. Retrieved 2020-09-04.
  22. ↑ MDNː Type coercion

Lesson 3 - Functions

This lesson introduces JavaScript functions.


Objectives and Skills

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

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

Multimedia

  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

  • W3Schools: JavaScript Functions
  • Javascript.info Function Basics
  • W3Schools: JavaScript Function Definitions
  • W3Schools: JavaScript Function Parameters
  • W3Schools: JavaScript Math Object
  • W3Schools: Javascript toFixed() - converts a number into a string, rounding to a specified number of decimals
  • Example Code
  • Mindsers Blog: How does the return statement work?
  • MozillaDeveloper: Functions - Javascript
  • JavaScript Inputs

Activities

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

  • 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

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 and is accessible from anywhere in a program.[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

  • Wikipedia: Modular programming
  • Wikipedia: Subroutine
  • Wikipedia: Parameter (computer programming)
  • Wikipedia: Scope (computer science)
  • Wikipedia: Naming convention (programming)
  • Function Declaration vs. Function Expression
  • JavaScript Functions — Understanding The Basics
  • MDN web docs - Functions
  • Codecademy: Functions
  • Mr. Bool: Understanding Random Function
  • TutorialsTeacher: JavaScript Function
  • JavaScript Info: Introduction to Browser Events
  • sebhastian.com: Return multiple values from JavaScript function call
  • W3Schools.com: Input types
  • W3Schools.com: HTML DOM Attribute value

References

  1. ↑ Microsoft: Exam 98-382 Introduction to Programming Using JavaScript
  2. ↑ Wikibooks: Programming Fundamentals/Practice: Data and Operators
  3. ↑ Wikibooks: Programming Fundamentals/Practice: Data and Operators
  4. ↑ W3Schools: JavaScript Functions
  5. ↑ https://google.github.io/styleguide/jsguide.html
  6. ↑ MDNː Functions — reusable blocks of code
  7. ↑ W3Schoolsː JavaScript Function Invocation
  8. ↑ W3Schoolsː JavaScript Function Definitions
  9. ↑ 9.0 9.1 W3Schoolsː JavaScript Function Parameters
  10. ↑ MDNː Functions — Return Values
  11. ↑ "JavaScript/Functions - Wikibooks, open books for an open world". en.wikibooks.org. Retrieved 2021-02-01.
  12. ↑ Example: "Tryit Editor v3.6". www.w3schools.com. Retrieved 2021-02-01.
  13. ↑ Wikibooks: JavaScript/Anonymous functions
  14. ↑ "JavaScript Function Parameters". www.w3schools.com. Retrieved 2019-09-05.
  15. ↑ "JavaScript Function Parameters". www.w3schools.com. Retrieved 2019-09-05.
  16. ↑ "JavaScript Functions". www.w3schools.com. Retrieved 2019-09-05.
  17. ↑ W3Schools: JavaScript Functions
  18. ↑ Singh, Mandeep (2017-10-11). "Function Declarations vs. Function Expressions". Medium. Retrieved 2020-09-08.
  19. ↑ W3Schools: JavaScript Scope
  20. ↑ W3Schools: JavaScript Functions
  21. ↑ Wikipedia: Local variable
  22. ↑ "JavaScript Function Parameters". www.w3schools.com. Retrieved 2019-09-05.
  23. ↑ W3Schools: Return
  24. ↑ Introduction to Programming/Scope
  25. ↑ MDN: Undefined

Lesson 4 - Events

This lesson introduces JavaScript events.


Objectives and Skills

Objectives and skills for this lesson include:[1]

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

Readings

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

Multimedia

  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

  • W3Schools: JavaScript Events
  • W3Schools: JavaScript HTML DOM Events
  • W3Schools: JavaScript HTML DOM Event Listener
  • Example Code
  • Events

Activities

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

  • 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

DOM (Document Object Model)
The HTML DOM represents the structure of a web page in a tree-like format, where each element, attribute, and piece of text in the page is represented as a "node." This allows developers to interact with the content, structure, and styles of the web page dynamically.[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

  • IdRatherBeWriting: Events and Listeners
  • MDN: Event Reference
  • W3Schools: Global Event Attributes
  • StackOverflow: HTML Event Attributes & Assign Events
  • Javascript.info - Introduction to browser events
  • MDN: Introduction to events
  • Eloquent JavaScript.net: Handling Events
  • TutorialRepublic: Understanding Event Listeners
  • JavaScript Event Handlers
  • geeksforgeeks: JavaScript Events
  • Kirupa: Javascript Events
  • JavaScript Tutorial: Handling Events in JavaScript
  • W3Schools: HTML <input> Tag
  • JavaScript Tutorial Input Event
  • W3Schools: HTML DOM Event Object
  • An Introduction to JavaScript Event Listeners for Web Designers

References

  1. ↑ Microsoft: Exam 98-382 Introduction to Programming Using JavaScript
  2. ↑ PythonLearn: Variables, expressions, and statements
  3. ↑ Wikibooks: Programming Fundamentals/Practice: Data and Operators
  4. ↑ Wikibooks: Programming Fundamentals/Practice: Data and Operators
  5. ↑ https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Building_blocks/Events
  6. ↑ https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Building_blocks/Events
  7. ↑ https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Building_blocks/Events
  8. ↑ https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Building_blocks/Events
  9. ↑ https://www.w3schools.com/js/js_htmldom_eventlistener.asp
  10. ↑ https://www.w3schools.com/js/js_htmldom_eventlistener.asp
  11. ↑ https://www.w3schools.com/js/js_htmldom_eventlistener.asp
  12. ↑ "Event (computing)". Wikipedia. 2021-01-12. https://en.wikipedia.org/w/index.php?title=Event_(computing)&oldid=999891699. 
  13. ↑ "JavaScript HTML DOM". www.w3schools.com. Retrieved 2019-09-15.
  14. ↑ https://www.w3schools.com/js/js_htmldom_events.asp
  15. ↑ "JavaScript/Event handling - Wikibooks, open books for an open world". en.wikibooks.org. Retrieved 2020-09-16.
  16. ↑ https://www.w3schools.com/js/js_htmldom_eventlistener.asp
  17. ↑ 17.0 17.1 17.2 17.3 "JavaScript Events". www.w3schools.com. Retrieved 2020-09-16.
  18. ↑ "JavaScript Events". www.w3schools.com. Retrieved 2020-09-16.
  19. ↑ 19.0 19.1 "JavaScript Events". www.w3schools.com. Retrieved 2020-09-16.

Lesson 5 - Conditions

This lesson introduces JavaScript conditions.


Objectives and Skills

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

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

Multimedia

  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

  • W3Schools: JavaScript Booleans
  • W3Schools: JavaScript if else and else if
  • W3Schools: JavaScript Switch Statement
  • JavaScript - Errors & Exceptions Handling
  • GeeksforGeeeks - Conditional Statements
  • Example Code
  • Stack Overflow: Using if else statements with a select form
  • Conditions

Activities

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

  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

  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

  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

  • 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.[11]
  • 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.[12]
  • The switch statement may have an optional default case. It specifies the block of code that runs if there is no case match.[13]
  • Conditional statements can be inside of other conditional statements, and can have multiple conditions to test.[14]
  • When writing conditions based on equality, "==" is used rather than "=", which is the assignment operator.[15]

Key Terms

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

See Also

  • Codeburst: The Conditional (Ternary) Operator Explained
  • Digital Ocean: How To Use the Switch Statement in JavaScript
  • JavaScript.com: JavaScript Conditions
  • JavaScript Info: Conditional operators
  • JavaScript Tutorial: If Else Statement
  • Kirupa: Conditional Statements: If and Else
  • Kirupa: Conditional Statements: Switch
  • MDN: Making Decisions in Your Code - Conditionals
  • Tutorial Gateway: JavaScript Nested If
  • W3Resource: JavaScript if...else statements
  • W3Resource: JavaScript switch statement
  • sebhastian.com: A guide to JavaScript if and else statements
  • sebhastian.com: JavaScript switch case statement guide (with examples)
  • W3Schools: JavaScript Comparison and Logical Operators
  • if...else - Javascript - MDN Web Docs - Mozilla

References

  1. ↑ Microsoft: Exam 98-382 Introduction to Programming Using JavaScript
  2. ↑ PythonLearn: Conditional Execution
  3. ↑ Wikibooks: Programming Fundamentals/Practice: Conditions
  4. ↑ Wikibooks: Programming Fundamentals/Practice: Conditions
  5. ↑ W3Schools: JavaScript if else and else if
  6. ↑ W3Schools: JavaScript if else and else i
  7. ↑ W3Schools: JavaScript if else and else i
  8. ↑ W3Schools: JavaScript if else and else i
  9. ↑ W3Schools: JavaScript switch Statement
  10. ↑ W3Schools: JavaScript switch Statement
  11. ↑ Zakas, Nicholas C. (2010). High Performance JavaScript. Sebastopol, California: O'Reilly Media. ISBN 978-1-4493-8874-4. 
  12. ↑ W3Schools: JavaScript switch Statement
  13. ↑ W3Schools: JavaScript switch Statement
  14. ↑ MDN | If... Else
  15. ↑ Rasi, D.; Indirani, M.. Web Technology. Tamil Nadu, India: Shanlax Publications. ISBN 978-93-88398-57-2. 
  16. ↑ https://www.w3schools.com/js/js_booleans.asp
  17. ↑ https://www.w3schools.com/js/js_switch.asp
  18. ↑ https://www.w3schools.com/js/js_comparisons.asp
  19. ↑ https://www.w3schools.com/js/js_if_else.asp
  20. ↑ https://www.w3schools.com/js/js_switch.asp
  21. ↑ https://www.w3schools.com/js/js_if_else.asp
  22. ↑ https://www.w3schools.com/js/js_if_else.asp
  23. ↑ https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/if...else
  24. ↑ https://www.w3schools.com/js/js_comparisons.asp
  25. ↑ https://www.educba.com/nested-if-in-javascript/
  26. ↑ "JavaScript Switch Statement". www.w3schools.com. Retrieved 2019-09-27.

Lesson 6 - While Loops

This lesson introduces JavaScript while and do while loops.


Objectives and Skills

Objectives and skills for this lesson include:[1]

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

Readings

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

Multimedia

  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

  • W3Schools: JavaScript While Loop
  • W3Schools: JavaScript Do/While Loop
  • Example Code
  • DigitalOcean: While Loops

Activities

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

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

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

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

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 is 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

  • areknawo.com: JavaScript Debugging Done Right
  • MDN web docs: The while statement
  • For, While and DO While LOOP in JavaScript (with Examples)
  • Tutorials Point: JavaScript While Loop
  • Difference between JavaScript While and Do While loop
  • GeeksforGeeks: Difference Between While and Do-While
  • Mozilla: JavaScript Do/While Loop
  • W3schools: Javascript While Loop
  • sebhastian.com: JavaScript while loop (with examples and use cases)
  • W3schools: JavaScript Comparison and Logical Operators
  • Programiz: While and Do While Loops Explained

References

  1. ↑ Microsoft: Exam 98-382 Introduction to Programming Using JavaScript
  2. ↑ 2.0 2.1 MDNː Loops and iteration
  3. ↑ Wikipedia: Don't repeat yourself
  4. ↑ Craie-programmingː Coding repetition
  5. ↑ CSULBː CECS 174, Loops
  6. ↑ Wikipediaː Infinite loop
  7. ↑ "while - JavaScript | MDN". developer.mozilla.org. Retrieved 2021-02-28.
  8. ↑ "Increment (++)". MDN Web Docs. Retrieved 2020-09-29.
  9. ↑ "Decrement (--) - JavaScript | MDN". developer.mozilla.org. Retrieved 2023-02-26.
  10. ↑ "JavaScript for Loop". www.w3schools.com. Retrieved 2023-02-26.
  11. ↑ JavaScript.info: While and For
  12. ↑ MDN: Loops and Iteration
  13. ↑ W3Schools: JavaScript for loop
JavaScript Programming

Lesson 7 - For Loops

This lesson introduces JavaScript for loops and nested loops.


Objectives and Skills

Objectives and skills for this lesson include:[1]

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

Readings

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

Multimedia

  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

  • W3Schools: JavaScript For Loop
  • W3Schools: JavaScript Break and Continue
  • Programiz: Javascript For Loop Examples
  • Example Code
  • FreeCodeCamp: For Loops

Activities

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

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

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

  • 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} ;
  • 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.

Key Terms

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

  • areknawo.com: JavaScript Debugging Done Right
  • DoFactory: JavaScript Loops
  • Mozzila: JavaScript for loops
  • GeeksforGeeks: Loops in JavaScript
  • Geeks for Geeks: JavaScript for loops
  • mikedane.com: For Loops
  • Tutorialspoint: JavaScript For Loop
  • W3schools: Javascript For Loop
  • sebhastian.com: JavaScript for loop guide with examples

References

  1. ↑ Microsoft: Exam 98-382 Introduction to Programming Using JavaScript
  2. ↑ 2.0 2.1 MDNː Loops and iteration
  3. ↑ Wikipedia: Don't repeat yourself
  4. ↑ Craie-programmingː Coding repetition
  5. ↑ CSULBː CECS 174, Loops
  6. ↑ Wikipediaː Infinite loop
  7. ↑ W3Schools: JavaScript For Loop
  8. ↑ W3Schools: JavaScript For Loop
  9. ↑ W3Schools: JavaScript For Loop
  10. ↑ FreeCodeCamp: JavaScript Loops Explained
  11. ↑ W3Schools: JavaScript break
  12. ↑ "JavaScript Break and Continue". www.w3schools.com. Retrieved 2020-10-06.
  13. ↑ 13.0 13.1 13.2 W3Schools: JavaScript for loop
  14. ↑ "For loop". Wikipedia. 2021-02-17. https://en.wikipedia.org/w/index.php?title=For_loop&oldid=1007384841. 
  15. ↑ EXL Skills: JavaScript Nested Loops

Lesson 8 - Arrays

This lesson introduces JavaScript arrays.


Objectives and Skills

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

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

Multimedia

  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

  • W3Schools: JavaScript Arrays
  • W3Schools: JavaScript Array Methods
  • W3Schools: JavaScript Sorting Arrays
  • W3Schools: JavaScript Array Iteration Methods
  • TutorialRepublic: JavaScript Arrays
  • The Modern Javascript Tutorial: Arrays
  • Example Code
  • Arrays | MDN Web Docs
  • Average or Arithmetic mean of an array using Javascript

Activities

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

  • 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

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 criteria.[13]

See Also

  • GeeksforGeeks: How to Create Two-Dimensional Arrays in JS
  • GeeksforGeeks: JavaScript Basic Array Methods
  • GeeksforGeeks: Ways of iterating over an array in JavaScript
  • JavaScript Tutorial: The Beginner's Guide to JavaScript Array with Examples
  • JavaScript.info: Arrays
  • Medium: JavaScript Multi-Dimensional Arrays
  • TutorialsPoint: JavaScript - the Arrays Object
  • W3Resource: Array Exercise
  • Khan Academy - Intro to Arrays
  • JavaScript Array indexOf() Method
  • sebhastian.com: Understanding JavaScript 2D array
  • sebhastian.com: Filter JavaScript array element with multiple conditions
  • TheModernJavaScript: JavaScript Arrays

References

  1. ↑ Microsoft: Exam 98-382 Introduction to Programming Using JavaScript
  2. ↑ 2.0 2.1 2.2 2.3 2.4 https://www.dyn-web.com/javascript/arrays/multidimensional.php
  3. ↑ "Indexed collections - JavaScript | MDN". developer.mozilla.org. Retrieved 2021-03-16.
  4. ↑ https://www.w3schools.com/js/js_arrays.asp
  5. ↑ https://www.w3schools.com/js/js_array_methods.asp
  6. ↑ https://www.w3schools.com/jsref/jsref_indexof_array.asp
  7. ↑ https://www.w3schools.com/jsref/jsref_obj_array.asp
  8. ↑ https://www.w3schools.com/jsref/jsref_length_array.asp
  9. ↑ https://www.dyn-web.com/javascript/arrays/multidimensional.php
  10. ↑ "JavaScript Array Methods". www.w3schools.com. Retrieved 2020-10-13.
  11. ↑ "JavaScript Array Iteration Methods". www.w3schools.com. Retrieved 2021-03-11.
  12. ↑ https://www.w3schools.com/js/js_array_sort.asp
  13. ↑ https://sebhastian.com/javascript-filter-array/

Lesson 9 - Date and Time

This lesson introduces JavaScript objects using dates.


Objectives and Skills

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

  1. Wikibooks: JavaScript/Dates

Multimedia

  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

  • W3Schools: JavaScript Date Objects
  • W3Schools: JavaScript Date Formats
  • W3Schools: JavaScript Date Get Methods
  • W3Schools: JavaScript Date Set Methods
  • W3Schools: Timing Events
  • JavaScript Get Date Methods
  • w3schools: Date Format For Date Picker
  • W3Schools: Javascript Date Examples
  • StackOverflow: How to update time regularly
  • Example Code

Activities

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

  • 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

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

  • Digital Ocean: Understanding Date and Time in JavaScript
  • JavaScript.Info: Date and time
  • Javascripture.com: Date
  • MDN: input type="date"
  • MDN: Date
  • Phoenix Nap: Date and Time
  • Toptal: Date and Time
  • W3Schools: JavaScript Date Formats
  • MDN: input type="number"
  • The Modern Javascript

References

  1. ↑ Microsoft: Exam 98-382 Introduction to Programming Using JavaScript
  2. ↑ W3Schools: JavaScript Date Reference
  3. ↑ 3.0 3.1 3.2 W3Schoolsː JavaScript Date Objects
  4. ↑ W3Schools: JavaScript Date Methods
  5. ↑ W3Schools: JavaScript Set Date Methods
  6. ↑ W3Schools: JavaScript Timing Events
  7. ↑ "Date - JavaScript | MDN". developer.mozilla.org. Retrieved 2021-03-26.
  8. ↑ Epoch & Unix Timestamp
  9. ↑ "JavaScript Date Formats". www.w3schools.com. Retrieved 2023-03-17.
  10. ↑ "Date JavaScript API". www.javascripture.com. Retrieved 2020-10-20.
  11. ↑ [1]
  12. ↑ [2]
  13. ↑ [3]
  14. ↑ W3Schools: Universal Coordinated Time

Lesson 10 - Objects

This lesson introduces JavaScript objects.


Objectives and Skills

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

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

Multimedia

  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

  • W3Schools: JavaScript Objects
  • W3Schools: JavaScript Object Properties
  • W3Schools: JavaScript Object Methods
  • W3Schools: JavaScript Object Constructors
  • Example Code

Activities

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

  • 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

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

  • AppDividend: Javascript Object.Keys() Example| Javascript Object Keys
  • Fireship.io: Objects
  • JavaScript Tutorial: JavaScript Objects
  • JavaScript.info: Objects
  • MDN: Working with Objects
  • SitePoint: JavaScript Object-Oriented Programming
  • SitePoint: Sort an Array of Objects in JavaScript
  • TutorialRepublic JavaScript Objects - Manipulating by Value vs. Reference
  • TutorialsPoint: What is the difference between a method and a function
  • W3Resource: JavaScript Object Exercises
  • JavaScript.Info: Objects
  • MDN: Javascript Objects
  • How to Pass an Object as a Parameter in Javascript Function
  • W3Schools: JavaScript String Split Method
  • Stack OverFlow: Set of Objects

References

  1. ↑ Microsoft: Exam 98-382 Introduction to Programming Using JavaScript
  2. ↑ EasyBib:APA Book Reference
  3. ↑ EasyBib:MLA Book Reference
  4. ↑ 4.0 4.1 W3Schoolsː JavaScript Objects
  5. ↑ 5.0 5.1 MDNː JavaScript object basics
  6. ↑ MDNː Property accessors
  7. ↑ https://www.w3schools.com/js/js_object_definition.asp
  8. ↑ https://www.w3schools.com/js/js_objects.asp
  9. ↑ https://www.w3schools.com/js/js_object_definition.asp
  10. ↑ https://www.geeksforgeeks.org/javascript-object-properties
  11. ↑ https://www.w3schools.com/js/js_objects.asp

Lesson 11 - DOM and BOM

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


Objectives and Skills

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

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

Multimedia

  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

  • W3Schools: JavaScript HTML DOM
  • W3Schools: JavaScript HTML DOM Methods
  • W3Schools: JavaScript DOM Document
  • W3Schools: JavaScript Browser Document Model (BOM)
  • W3Schools: JavaScript Window Screen
  • W3Schools: JavaScript Nodes
  • W3Schools: onresize Event
  • Example Code

Activities

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

  • 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

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

  • CSS Object Model
  • DotNetTricks: Understanding DOM and BOM
  • JavaScript Tutorial: JavaScript BOM
  • TutorialRepublic: JavaScript DOM Styling
  • JavaScript Tutorial: DOM & BOM Revisited
  • JavaScript Tutorial: DOM and BOM
  • DOM vs BOM in JavaScript
  • JavaScript Info: Browser Environment
  • MDN: Manipulating Documents
  • onresize Event
  • W3Schools: HTML Geolocation API
  • GeeksForGeeks: Difference Between DOM & BOM?

References

  1. ↑ Microsoft: Exam 98-382 Introduction to Programming Using JavaScript
  2. ↑ w3schools: JavaScript HTML DOM<
  3. ↑ w3schools: JavaScript Window
  4. ↑ w3schools: HTML DOM Elemenets
  5. ↑ EJ Mediaː JavaScript Tutorial for Beginners - 40 - Traversing the DOM
  6. ↑ w3schools: HTML DOM
  7. ↑ "JavaScript Window". www.w3schools.com. Retrieved 2021-04-02.
  8. ↑ w3schools: JavaScript Window
  9. ↑ MDN: DOM Introduction
  10. ↑ "JavaScript DOM Nodes". www.w3schools.com. Retrieved 2023-04-08.
  11. ↑ "JavaScript DOM Navigation". www.w3schools.com. Retrieved 2023-04-08.

Lesson 12 - Dynamic HTML

This lesson introduces dynamic HTML.


Objectives and Skills

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

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

Multimedia

  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

  • W3Schools: JavaScript HTML DOM - Changing HTML
  • W3Schools: JavaScript HTML DOM - Changing CSS
  • W3Schools: JavaScript HTML DOM Animation
  • W3Schools: JavaScript HTML DOM Navigation
  • W3Schools: JavaScript HTML DOM Elements (Nodes)
  • W3Schools: JavaScript HTML DOM Collections
  • W3Schools: JavaScript HTML DOM Node Lists
  • Example Code

Activities

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

  • 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.
  • 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 common method of creating new elements to HTML using JavaScript.

Key Terms

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 Also

  • Dev To: Add Dynamic Styling to HTML Elements
  • Geeks for Geeks: Dynamic HTML Introduction
  • InformIT: Understanding Dynamic Websites and HTML5 Applications
  • JavaScript.info: Modifying the document
  • Lifewire: How Dynamic HTML (DHTML) Is Used to Create Interactive Pages
  • TutorialRepublic: JavaScript DOM Get Set Attributes
  • Way2tutorial: Dynamic HTML
  • JavaScript Info: Document
  • MDN Web Docs: setAttribute() Method

References

  1. ↑ Microsoft: Exam 98-382 Introduction to Programming Using JavaScript
  2. ↑ https://www.w3schools.com/js/js_htmldom_navigation.asp
  3. ↑ W3Schoolsː JavaScript HTML DOM Navigation
  4. ↑ 4.0 4.1 W3Schoolsː JavaScript HTML DOM Elements (Nodes)
  5. ↑ https://www.geeksforgeeks.org/dhtml-introduction/
  6. ↑ https://www.w3.org/2003/01/dom2-javadoc/org/w3c/dom/Node.html
  7. ↑ https://www.w3schools.com/js/js_htmldom_nodelist.asp
  8. ↑ https://www.w3schools.com/js/js_htmldom_navigation.asp

Lesson 13 - Forms and Security

This lesson introduces JavaScript form processing and security.


Objectives and Skills

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

  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

  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

  1. w.youtu
  1. be.com/watch?v=30VeUWxZjS8
  • W3Schools: JavaScript Forms
  • W3Schools: HTML Form Attributes
  • W3Schools: JavaScript Validation API
  • W3Schools: Enctype in Form tag
  • W3Schools: JavaScript RegExp Reference
  • Example Code

Activities

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

  • Forms are an HTML element with some unique properties and events that allow programmers to inspect and control the form through JavaScript.
  • 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

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

  • How To Create: JavaScript Security
  • JavaScript Tutorial: Javascript Form Validation
  • Medium: 11 things developers should know about GET vs POST
  • MDN: Input Validation
  • MDN: HTML attribute: Pattern
  • MDN: Constraint Validation
  • Smashing Magazine: Form Validation Best Practices
  • JavaScript Info: Form Elements
  • How to Build HTML Forms Right: User Experience

References

  1. ↑ Microsoft: Exam 98-382 Introduction to Programming Using JavaScript
  2. ↑ https://www.w3schools.com/js/js_validation_api.asp
  3. ↑ 3.0 3.1 MDNː Form data validation
  4. ↑ 4.0 4.1 "HTTP Methods GET vs POST". www.w3schools.com. Retrieved 2023-04-22.
  5. ↑ https://www.w3schools.com/tags/att_input_pattern.asp
  6. ↑ https://developer.mozilla.org/en-US/docs/Web/API/HTMLFormElement/reportValidity
  7. ↑ https://www.w3schools.com/tags/att_input_required.asp
  8. ↑ https://developer.mozilla.org/en-US/docs/Web/API/HTMLSelectElement/setCustomValidity
  9. ↑ https://developer.mozilla.org/en-US/docs/Web/API/ValidityState

Lesson 14 - AJAX and JSON

This lesson introduces AJAX and JSON.


Objectives and Skills

Objectives and skills for this lesson include:

  • Send and receive JSON data using AJAX

Readings

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

Multimedia

  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

  • W3Schools: AJAX Introduction
  • W3Schools: JSON Introduction
  • Example Code

Activities

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

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

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

  • Server-Side Scripting
  • GeeksforGeeks: Difference Between JSON and AJAX
  • Happy Coding: AJAX AND JSON
  • Medium: Using JSON and AJAX in JavaScript
  • MDN Cross-Origin Resource Sharing (CORS)
  • TutorialRepublic: JavaScript Ajax
  • JSON Tutorial - Learn How to Use JSON with JavaScript
  • Webucator how to make get post head requests using AJAX
  • List of HTTP status codes

References

  1. ↑ JSON.org
  2. ↑ https://en.wikipedia.org/wiki/Ajax_(programming)
  3. ↑ https://en.wikipedia.org/wiki/Ajax_(programming)
  4. ↑ https://www.tutorialrepublic.com/javascript-tutorial/javascript-json-parsing.php
  5. ↑ https://www.w3schools.com/js/js_json_intro.asp
  6. ↑ https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/onreadystatechange
  7. ↑ https://www.w3schools.com/tags/ref_httpmethods.asp
  8. ↑ https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest

Lesson 15 - Libraries and Frameworks

This lesson introduces JavaScript libraries and frameworks.


Objectives and Skills

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

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

Multimedia

  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

  • W3Schools: jQuery
  • W3Schools: Angular
  • W3Schools: React
  • W3Schools: W3.JS
  • Vue.js: Guide
  • W3schools: Bootstrap: getting started

Activities

  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

  • 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

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

  • FreeCodeCamp: The Difference Between a Framework and a Library
  • List of 10 Best Front end Frameworks to Use For Web Development
  • Software Framework vs Library

References

  1. ↑ 1.0 1.1 "Wikipedia: Web framework".
  2. ↑ "GeeksForGeeks: Software Framework vs Library".
  3. ↑ Khan Academy: What's a JS library?

Lesson 16 - Node.js REST API

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


Objectives and Skills

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

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

Multimedia

Examples

  • W3Schools: Node.js Tutorial
  • W3Schools: RESTful Web Services
  • Hello World
  • REST API

Activities

  1. Install Node.js
    • Review Medium: Building a simple REST API with NodeJS and Express.
    • Download and install Node.js
    • Use a command prompt or terminal window to verify Node.js installation:
          node -v
          npm -v
  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
    • Copy the REST API example code to create a REST API website.
    • Start the website using the command:
          node server.js
    • Revise your JavaScript Programming/AJAX and JSON project to send data to your Express.js server.

Lesson Summary

  • Bullet points

Key Terms

term
definition

See Also

References

Retrieved from "https://en.wikiversity.org/w/index.php?title=JavaScript_Programming/Collection&oldid=2184221"
Categories:
  • JavaScript
  • Technology courses
  • Computer programming
  • Tertiary Education
  • Resources needing facts checked
  • JavaScript Programming
  • Web development
  • Node.js
You are visitor 01402503 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.