JavaScript Programming/Collection
JavaScript Programming
[edit | edit source]
JavaScript, often abbreviated as JS, is a high-level, interpreted programming language that conforms to the ECMAScript specification. It is a programming language that is characterized as dynamic, weakly typed, prototype-based and multi-paradigm.[1]
Alongside HTML and CSS, JavaScript is one of the core technologies of the World Wide Web. JavaScript enables interactive web pages and is an essential part of web applications. The vast majority of websites use it, and major web browsers have a dedicated JavaScript engine to execute it.[2]
This course comprises 16 lessons on JavaScript programming. Each lesson includes a combination of Wikipedia and Internet-based readings, YouTube videos, and hands-on learning activities. The entire course can be downloaded in book form by selecting Download Learning Guide in the sidebar.
Preparation
[edit | edit source]This is a second-semester, college-level course. Learners should already be familiar with introductory web development concepts, including HTML and CSS, and have advanced or proficient-level computer skills.
Lessons
[edit | edit source]- Introduction
- Variables and Expressions
- Functions
- Events
- Conditions
- While Loops
- For Loops
- Arrays
- Date and Time
- Objects
- DOM and BOM
- Dynamic HTML
- Forms and Security
- AJAX and JSON
- Libraries and Frameworks
- Node.js REST API
See Also
[edit | edit source]- 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
[edit | edit source]- Wikibooks: JavaScript
- Eloquent JavaScript: A Modern Introduction to Programming
- https://javascript.info/
References
[edit | edit source]Lesson 1 - Introduction
[edit | edit source]This lesson introduces the JavaScript programming language and environments.
Objectives and Skills
[edit | edit source]Objectives and skills for this lesson include:[1]
- Apply JavaScript best practices
- Comments; indentations (code formatting); naming conventions; noscript; constants; reserved keywords; debugger keyword; setting breakpoints; console.log
- Evaluate the use of inline and external scripts
- When to use, how to use, and what happens when both are used
Readings
[edit | edit source]- Wikibooks: JavaScript/Introduction
- Wikibooks: JavaScript/First program
- Wikibooks: JavaScript/Placing the code
- CodeCademy: File Paths
Multimedia
[edit | edit source]- YouTube: JavaScript Tutorial for Beginners - 01 - Introduction
- YouTube: JavaScript Tutorial for Beginners - 02 - Statements
- YouTube: JavaScript Tutorial for Beginners - 05 - Using an external file
- YouTube: JavaScript - Output
- YouTube: Beginner JavaScript Tutorial - 2 - Comments and Statements
- YouTube: JavaScript - How to use the console in a browser
- YouTube: noscript Tag - JavaScript Programming
- YouTube: Using Alert & Console.log in JavaScript
- YouTube: JavaScript for Beginners — Console Logging
- YouTube: Clean Code: Formatting and Comments
- YouTube: Javascript The innerHTML property
- YouTube: javascript: part1, console.log, getElementByID & innerHTML
- YouTube: JavaScript Loading Strategies (async and defer)
- Youtube: JavaScript DOM Tutorial #4 - The Query Selector
- Youtube: The innerText vs. textContent properties in JavaScript
Examples
[edit | edit source]To test the following examples, copy the code and paste it in the body of an HTML file and view the file in a browser, or use a JavaScript test environment such as W3Schools: Tryit Editor.
document.write()
[edit | edit source]document.write()
writes a string of text to a document stream.
<script> document.write("Hello World"); </script>
window.alert()
[edit | edit source]window.alert()
displays an alert box with an optional message and an OK button.
<script> document.alert("Hello World"); </script>
innerHTML and InnerText
[edit | edit source]The innerHTML
and innerText
returns or sets the inner HTML and text of an element, respectively.
<p id="id-name"> This text will be replaced</p> <script> document.getElementById("id-name").innerHTML = "Hello World"; </script>
console.log()
[edit | edit source]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
[edit | edit source]- 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 asalert()
).window.alert()
is best practice. - Use
document.getElementById().innerText
ordocument.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]
- Use
- Using the Hello program above, test JavaScript code placement in a variety of ways:
- Use
<script>
in<head>
for thedocument.write()
- Use
<script>
in<body>
for thewindow.alert()
- Use
<script src="...">
in<head>
or<body>
for thedocument.getElementById().innerText
ordocument.getElementById().innerHTML
andconsole.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
- Use
- Add comments to the external JavaScript src code above, describing the program.
- 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. - Research best practices for where to place JavaScript code and how to format and structure it (style guides).
- Research the difference between
<script async ...>
and<script defer ...>
.
Lesson Summary
[edit | edit source]- 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
ordefer
attributes.[14] - The
async
attribute indicates that the browser should, if possible, load the script asynchronously. The script is executed as soon as it is loaded.[15] - The
defer
attribute indicates that the browser should, if possible, load the script asynchronously. The script is executed after the document has been parsed.[16] - The
Document.write()
method writes a string of text to a document stream.[17] - The
Window.alert()
method displays an alert dialog with the optional specified content and an OK button.[18] - The
document.getElementById()
method returns an Element object representing the element whose id property matches the specified string.[19] - The Element
innerHTML
property gets or sets the HTML or XML markup contained within the element.[20] - The HTML Element
innerText
property represents the text content of a node and its descendants.[21] - The
console.log()
method outputs a message to the web console.[22]
Key Terms
[edit | edit source]- 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
[edit | edit source]- What are three different ways to implement JavaScript into an HTML file?
- Is it mandatory to end a statement with a semicolon in JavaScript?
- What can you do with
document.getElementById()
in JavaScript? - How do you create a windowed message with JavaScript?
- What is a common use for comments during code testing?
- How do you embed JavaScript code in an HTML file?
- What is
<noscript>
used for? - Why is linking to external scripts considered the best practice for script placement?
- Where is the best place to put <script></script> for faster loading webpages?
- What is the difference between defer and async?
See Also
[edit | edit source]- 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
[edit | edit source]- ↑ Microsoft: Exam 98-382 Introduction to Programming Using JavaScript
- ↑ Chrome DevTools/
- ↑ MDNː Browser Console
- ↑ MSDNː Using keyboard shortcuts
- ↑ Safari Developer Helpː Developer Tools overview
- ↑ Wikipedia: JavaScript
- ↑ MDN: JavaScript Guide
- ↑ MDN: noscript
- ↑ MDN: script
- ↑ MDN: script
- ↑ MDN: Author Fast-Loading HTML Pages
- ↑ MDN: Author Fast-Loading HTML Pages
- ↑ MDN: Use JavaScript Within a Webpage
- ↑ MDN: script
- ↑ MDN: script
- ↑ MDN: script
- ↑ MDN: Document.write
- ↑ MDN: Window.alert
- ↑ MDN: Document.getElementById
- ↑ MDN: innerHTML
- ↑ MDN: innerText
- ↑ MDN: console.log
- ↑ {{Cite web|url= https://www.geeksforgeeks.org/console-in-javascript/#:~:text=In%20javascript%2C%20the%20console%20is,error()
- ↑ "Definition of JavaScript | Dictionary.com". www.dictionary.com. Retrieved 2021-01-22.
- ↑ "JavaScript Comments". www.w3schools.com. Retrieved 2020-08-26.
- ↑ Wikipedia: EMCAScript
- ↑ {{Cite web|url= https://developer.mozilla.org/en-US/docs/Web/HTML/Element/noscript
Lesson 2 - Variables and Expressions
[edit | edit source]This lesson introduces JavaScript variables, data types, expressions, and operators.
Objectives and Skills
[edit | edit source]Objectives and skills for this lesson include:[1]
- Apply JavaScript best practices
- Comments; indentations; naming conventions; noscript; constants; reserved keywords; debugger keyword; setting breakpoints; console.log
- Declare and use variables of primitive data types
- Number; Boolean; String; Null; Undefined; typeof operator; type checking functions; use strict; converting between data types; formatting numbers; string operations; single quote vs double quote (nesting); initialization
- Complete or debug code that uses assignment and arithmetic operators
- Assignment; increment; decrement; addition; subtraction; division; multiplication; modulus; compound assignment operators.
Readings
[edit | edit source]- Wikibooks: JavaScript/Variables and types
- Wikibooks: JavaScript/Numbers
- Wikibooks: JavaScript/Strings
- Wikibooks: JavaScript/Operators
Multimedia
[edit | edit source]- Variables
- YouTube: JavaScript Tutorial for Beginners - 03 - Variables
- YouTube: JavaScript Tutorial for Beginners - 04 - Variables Part 2
- YouTube: JavaScript Programming Tutorial 6 - Variables and Expressions
- YouTube: JavaScript Let, Const & Var
- YouTube: 7: How to Create Variables in JavaScript | JavaScript Tutorial | Learn JavaScript
- YouTube: What is a Variable? | JavaScript in less-than 3 minutes
- YouTube: Variables & Data Types | Javascript | Tutorial 6
- Data Types and Operators
- YouTube: Javascript Variables & Data Types
- YouTube: JavaScript Tutorial for Beginners - 08 - Operators
- YouTube: A Basic Calculator
- YouTube: 20 String Methods in 7 Minutes
- Input
- YouTube: Getting User Input | Javascript | Tutorial 9
- YouTube: How to accept JavaScript USER INPUT in 5 minute
- Debugging
- YouTube: Debugging JavaScript (Google Chrome and Visual Studio Code)
- YouTube: Firefox JavaScript Debugger
- YouTube: Debugging JavaScript - Chrome DevTools 101
- Type Coercion
- Expressions vs. Statements
Examples
[edit | edit source]- 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
[edit | edit source]Complete two of the following activities using external JavaScript code. Apply JavaScript best practices, including comments, naming conventions, and constants. In at least one program, prompt the user for input and use console.log() for output. In another program, prompt the user for input and use document.getElementById().innerText or document.getElementById().innerHTML for output. Use the strict directive. Create test data to validate the accuracy of each program. Add comments at the top of the program and include references to any resources used.
Arithmetic
[edit | edit source]- 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]
- 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.
- 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.
- 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.
- 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]
- Review MathsIsFun: Order of Operations. Create a program that demonstrates the order of operations. Include parentheses, exponents, multiplication, division, addition, and subtraction in your program. Use variables for the calculations and label the output. For example, part of the program might display:
1 + 2 * 3 = 7
(1 + 2) * 3 = 9
...
Data Types
[edit | edit source]- 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. - Create a program that demonstrates string operations and string formatting. Define string constants or string literals that include apostrophes ('). Define string constants or string literals that include "quotes". Convert between string and numeric data types using Number() and .toFixed() with two decimal places. Concatenate string literals and variables to display output.
Debugging
[edit | edit source]- 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. - Add a breakpoint to the program somewhere after the
debugger
statement. After the program stops with the debugger, resume script execution and observe the script stopping at the breakpoint.
Lesson Summary
[edit | edit source]- By convention, JavaScript variable names are written in camelCase.[4]
- In JavaScript, I explored variable declarations with
let
andconst
, string properties and methods such aslength
andtoUpperCase()
, primitive data types likenumber
,string
,boolean
,null
, andundefined
, and various operators for string concatenation, arithmetic, assignment, increments, comparisons, and logical evaluations. - JavaScript Class, interface, record, and typedef names are often written in Title Case.[4]
- JavaScript constant names are written in UPPER_CASE.[5]
- JavaScript variable and constant names must be unique. These unique names are called identifiers.[6]
- Reserved words (for example, continue, debugger, break, etc.) can't serve as variable names.[6]
- Names can begin only with a letter, an underscore or a dollar sign. Names are allowed to contain numbers, but a number can't be the first character.[6]
- In Java Script names are case sensitive.[6]
- Comments, which are annotations or explanations of written code[7], are done in JavaScript using // for a single line, and /* ... */ for multiple lines.
- JavaScript has 7 data types: Number, String, Boolean, Null, Undefined, Function, and Object. Null and Undefined data types can't contain values.[8]
- There are 6 types of objects in JavaScriptː Object, Date, Array, String, Number and Boolean.[8]
- JavaScript has only 1 type of number.[9]
- With some other languages, like Java and C, there is a special “character” type. JavaScript consists of only one type, string.[10]
- The
typeof
operator is used to find the data type of the variable.[8] - JavaScript has built-in functions to work with strings and numbers[11]
- Strings are written using single or double quotation marks. Quotation marks can be used inside the string if they don't match the ones outside of it.[8] Quotation marks used inside can match the outside ones only if they are preceded by the backslash escape character.[12]
- You can convert between data types in JavaScript.[8]
- "use strict" is a literal expression that requires / enforces variable declaration. It allows for cleaner code to be written.[13]
Key Terms
[edit | edit source]- 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[16]
- Title case or pascal case
- Method of joining multiple words into one variable name where the first letter of every word is capitalized.[16]
- concatenation
- Method of joining two strings, data, or other text together in programming. In JavaScript, strings are concatenated using the '+' operator. [17]
- console.log
- A function in JavaScript which is used to print any kind of variables defined before in it or to just print any message that needs to be displayed to the user.
- constant
- A keyword introduced from ES2015, It is a container for storing a permanent data value that cannot be changed later in the program.[18]
- Equality
- An operator referencing when two values are equal, "==", this is distinct from the assignment ("=") operator referenced above.[18]
- let
- A keyword introduced from ES2015, It is used to declare a variable in JavaScript. it is used as block scoped variable while "var" is used as a function scope variable [19]
- null
- A special value which represents "nothing." It is not a reference to a null pointer.[15]
- number
- Data type in JavaScript which represents both integers and floating-point value.[15]
- object
- A variable that can contain many values.[20]
- order of operations
- A set of rules for for evaluating mathematical expressions. While different programming languages have different rules for precedence, the order of operations start from greatest precedence with parentheses, exponents, multiplication/division, and addition/subtraction.[21]
scope
The current context of the code, refers to the accessibility of functions and variables.
- string
- Can consist of one character or many. A string must be surrounded by quotation marks.[15]
- type coercion
- The automatic or implicit conversion of values from one data type to another (such as strings to numbers).[22]
- undefined
- A variable which has not been assigned a value. If a variable is simply declared, but not assigned anything, it becomes undefined.[15]
- variable
- A container for storing a data values. Variables are used to hold values in expressions. [6]
See Also
[edit | edit source]- 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
[edit | edit source]- ↑ Microsoft: Exam 98-382 Introduction to Programming Using JavaScript
- ↑ PythonLearn: Variables, expressions, and statements
- ↑ Wikibooks: Programming Fundamentals/Practice: Data and Operators
- ↑ 4.0 4.1 https://google.github.io/styleguide/jsguide.html
- ↑ https://google.github.io/styleguide/jsguide.html
- ↑ 6.0 6.1 6.2 6.3 6.4 W3Schoolsː JavaScript Variables
- ↑ "Comment (computer programming)". Wikipedia. 2021-01-08. https://en.wikipedia.org/w/index.php?title=Comment_(computer_programming)&oldid=999054165.
- ↑ 8.0 8.1 8.2 8.3 8.4 W3Schoolsː JavaScript Data Types
- ↑ W3Schoolsː JavaScript Numbers
- ↑ "Data types". javascript.info. Retrieved 2019-09-05.
- ↑ MDN Web Docs: Data Types and Data Structures
- ↑ W3Schoolsː JavaScript Strings
- ↑ W3Schoolsː JavaScript Use Strict
- ↑ "JavaScript Arrays". www.w3schools.com. Retrieved 2024-03-08.
- ↑ 15.0 15.1 15.2 15.3 15.4 JavaScript.Infoː Data Types
- ↑ 16.0 16.1 Microsoft: Capitalization Styles
- ↑ "What is Concatenate?". www.computerhope.com. Retrieved 2020-09-04.
- ↑ 18.0 18.1 W3Schools: JavaScript const
- ↑ "JavaScript Let". www.w3schools.com. Retrieved 2020-09-01.
- ↑ W3Schoolsː JavaScript Objects
- ↑ "Programming Fundamentals/Order of Operations - Wikibooks, open books for an open world". en.wikibooks.org. Retrieved 2020-09-04.
- ↑ MDNː Type coercion
Lesson 3 - Functions
[edit | edit source]This lesson introduces JavaScript functions.
Objectives and Skills
[edit | edit source]Objectives and skills for this lesson include:[1]
- Complete and debug code that uses built-in Math functions
- Random; round; abs; floor; ceiling; min; max; pow; sqrt
- Complete and debug a function that accepts parameters and returns a value
- Reusable code; local versus global scope, redefine variables, pass parameters, value versus reference, return
Readings
[edit | edit source]- Wikibooks: JavaScript/Functions
- Wikibooks: JavaScript/Anonymous functions
- Mozilla: JavaScript/Functions
- JavaScript Functions
Multimedia
[edit | edit source]- YouTube: JavaScript Functions
- YouTube: JavaScript Tutorial for Beginners - 06 - Functions
- YouTube: JavaScript Tutorial for Beginners - 07 - Functions Part 2
- YouTube: JavaScript Tutorial for Beginners - 14 - Return statement
- YouTube: JavaScript Tutorial for Beginners - 15 - Global and local variables
- YouTube: JavaScript Tutorial for Beginners - 16 - Pass by value
- YouTube: Passing by reference vs. by value - JavaScript Tutorial
- YouTube: JavaScript Functions & Parameters
- YouTube: Number Methods and Math Objects in JavaScript
- YouTube: How to Create JavaScript Functions
- YouTube: Functions and Return
- How To Create/Use Functions - JavaScript Essentials
Examples
[edit | edit source]- 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
[edit | edit source]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.
- 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.
- 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.
- 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.
- 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.
- 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]
- Create a program that helps the user determine how much paint is required to paint a room and how much it will cost. Ask the user for the length, width, and height of a room, the price of a gallon of paint, and the number of square feet that a gallon of paint will cover. Calculate the total area of the four walls as
2 * length * height + 2 * width * height
. Calculate the number of gallons as:total area / square feet per gallon
. Note: You must round up to the next full gallon. To round up, use the Math.ceil function. Calculate the total cost of the paint as:gallons * price per gallon
.[3]
Lesson Summary
[edit | edit source]- A JavaScript function is a block of code designed to perform a particular task.[4]
- Indent JavaScript code blocks (functions, conditions, loops, comment blocks, etc.) 2 spaces for each indent level.[5]
- Functions break down code into reusable blocks of code each of which performs a specific task.[6]
- Code inside a function is not executed at the time of declaration. A function has to be called upon (invoked) first.[7]
- JavaScript function expressions can invoke themselves.[8]
- JavaScript functions do not check the number of arguments received. Missing arguments are set to
undefined
.[9] - JavaScript functions do not check the data type of passed arguments.[9]
- JavaScript functions can only return one value.[10]
- A key benefit to using functions is that breaking. program down into smaller, simpler tasks makes it more manageable and maintainable.[11]
- Functions can be used as values.[12]
Key Terms
[edit | edit source]- anonymous function
- A function that was declared without any named identifier to refer to it. As such, an anonymous function is usually not accessible after its initial creation.[13]
- argument
- The real value passed to (and received by) the function.[14]
- arguments object
- An array of the arguments passed in when the function is invoked. The arguments object can be used to access arguments when more arguments are passed to the function than parameters declared by the function definition.[15]
- function
- A block of code designed to perform a particular task when the code is invoked. A JavaScript function can be defined using the function keyword.[16]
- function call
- The declaration of the function by its self doesn't do anything. In order to execute that code, the function must be called using the name given when the function was declared, and parenthesis "()" with parameters if needed.[17]
- function expression
- A function that can be stored in a variable. After a function expression has been stored in a variable, the variable can be used as a function. Functions stored in variables do not need function names. They are always invoked (called) using the variable name.[18]
- global variable
- A variable declared outside a function.[19]
- invocation
- The code inside the function will execute when "something" invokes (calls) the function.[20]
- local variable
- A local variable is a variable which is either a variable declared within the function or is an argument passed to a function.[21]
- parameter
- A name listed in a function definition.[22]
- return
- Ends function execution and returns a value in the place the function was invoked.[23]
- scope
- Refers to the visibility of variables and methods in one part of a program to another part of that program (local and global variables).[24]
- undefined
- The undefined property indicates that a variable has not been assigned a value, or not declared at all. It is a variable in global scope.[25]
See Also
[edit | edit source]- 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
[edit | edit source]- ↑ Microsoft: Exam 98-382 Introduction to Programming Using JavaScript
- ↑ Wikibooks: Programming Fundamentals/Practice: Data and Operators
- ↑ Wikibooks: Programming Fundamentals/Practice: Data and Operators
- ↑ W3Schools: JavaScript Functions
- ↑ https://google.github.io/styleguide/jsguide.html
- ↑ MDNː Functions — reusable blocks of code
- ↑ W3Schoolsː JavaScript Function Invocation
- ↑ W3Schoolsː JavaScript Function Definitions
- ↑ 9.0 9.1 W3Schoolsː JavaScript Function Parameters
- ↑ MDNː Functions — Return Values
- ↑ "JavaScript/Functions - Wikibooks, open books for an open world". en.wikibooks.org. Retrieved 2021-02-01.
- ↑ Example: "Tryit Editor v3.6". www.w3schools.com. Retrieved 2021-02-01.
- ↑ Wikibooks: JavaScript/Anonymous functions
- ↑ "JavaScript Function Parameters". www.w3schools.com. Retrieved 2019-09-05.
- ↑ "JavaScript Function Parameters". www.w3schools.com. Retrieved 2019-09-05.
- ↑ "JavaScript Functions". www.w3schools.com. Retrieved 2019-09-05.
- ↑ W3Schools: JavaScript Functions
- ↑ Singh, Mandeep (2017-10-11). "Function Declarations vs. Function Expressions". Medium. Retrieved 2020-09-08.
- ↑ W3Schools: JavaScript Scope
- ↑ W3Schools: JavaScript Functions
- ↑ Wikipedia: Local variable
- ↑ "JavaScript Function Parameters". www.w3schools.com. Retrieved 2019-09-05.
- ↑ W3Schools: Return
- ↑ Introduction to Programming/Scope
- ↑ MDN: Undefined
Lesson 4 - Events
[edit | edit source]This lesson introduces JavaScript events.
Objectives and Skills
[edit | edit source]Objectives and skills for this lesson include:[1]
- Identify and handle HTML events
- onchange; onmouseover; onload; onclick; onmouseout; onkeydown
Readings
[edit | edit source]- Wikipedia: Event (computing)
- Wikibooks: JavaScript/Event handling
- Wikibooks: JavaScript/W3C event handlers
Multimedia
[edit | edit source]- YouTube: What are JavaScript Events?
- YouTube: JavaScript Tutorial for Beginners - 33 - Intro to events
- YouTube: JavaScript 2021 Tutorial 9 - Calling functions from events
- YouTube: JavaScript Tutorial for Beginners - 32 - Changing an image
- YouTube: JavaScript Tutorial for Beginners - 34 - The mouseover event
- YouTube: addEventListener() - Beau teaches JavaScript
- YouTube: JavaScript Questions: What is Event Delegation, Event Propagation, Event Bubbling?
- YouTube: A Complete Overview of JavaScript Events - All You Need To Know
- Simplilearn: Understand JavaScript Events with Examples
Examples
[edit | edit source]- W3Schools: JavaScript Events
- W3Schools: JavaScript HTML DOM Events
- W3Schools: JavaScript HTML DOM Event Listener
- Example Code
- Events
Activities
[edit | edit source]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.
- 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.
- 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.
- 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.
- 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]
- Create a program that helps the user determine how much paint is required to paint a room and how much it will cost. Ask the user for the length, width, and height of a room, the price of a gallon of paint, and the number of square feet that a gallon of paint will cover. Calculate the total area of the four walls as
2 * length * height + 2 * width * height
Calculate the number of gallons as:total area / square feet per gallon
Note: You must round up to the next full gallon. To round up, use the Math.ceil function. Calculate the total cost of the paint as:gallons * price per gallon
.[4]
Lesson Summary
[edit | edit source]- Events are actions or occurrences that happen in the system you are programming[5]
- Events occur when the user clicks a button, presses a key on the keyboard, submits a form, resizes the window, etc. JavaScript can detect and react to such events by executing the code.[6]
- Each available event has an event handler, which is a block of code (usually a JavaScript function that you as a programmer create) that will be run when the event fires. [7]
- For a start, it is not a good idea to mix up your HTML and your JavaScript, as it becomes hard to parse — keeping your JavaScript all in one place is better; if it is in a separate file you can apply it to multiple HTML documents.[8]
- Event propagation is a way of defining the element order when an event occurs. If you have one element inside a second element, and the user clicks on the first element, which element's "click" event should be handled first?[9]
- In bubbling the innermost element's event is handled first and then the outer.[10]
- In capturing the outer most element's event is handled first and then the inner[11]
- Data on events can include not only the type of event, but when it occurred and what caused it to occur. [12]
Key Terms
[edit | edit source]- DOM (Document Object Model)
- The HTML DOM model is constructed as a tree of objects. The DOM defines a standard for accessing documents.[13]
- event
- A function can be called when an event occurs such as the user clicking on an element. Some other examples of events in JavaScript are mouseover, mouseout, input, and onload.[14]
- event handler
- An event that can be handled is something happening in a browser window, including a document loading, the user clicking a mouse button, the user pressing a key, and the browser screen changing size. When a function is assigned to handle an event type, that function is run when an event of the event type occurs. Examples include "onclick" and "onmouseover"[15]
- event listener
- It is attached to an element and fires a function when the event is detected on the element. [16]
- onchange
- An HTML element has been changed such as a user changing an input field value. (Sometimes still have to hit enter on keyboard to trigger.)[17]
- onclick
- An HTML event when the user clicks an HTML element.[18]
- onkeydown
- An HTML event when the user pushes a keyboard key.[19]
- onload
- The browser has finished loading the page.[19]
- onmouseout
- The user moves the mouse away from an HTML element.[17]
- onmouseover
- An HTML event when the user moves the mouse over an HTML element.[17]
- Touch Event
- A set of HTML events that occur when a user touches a touch-based device.[17]
See Also
[edit | edit source]- 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
[edit | edit source]- ↑ Microsoft: Exam 98-382 Introduction to Programming Using JavaScript
- ↑ PythonLearn: Variables, expressions, and statements
- ↑ Wikibooks: Programming Fundamentals/Practice: Data and Operators
- ↑ Wikibooks: Programming Fundamentals/Practice: Data and Operators
- ↑ https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Building_blocks/Events
- ↑ https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Building_blocks/Events
- ↑ https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Building_blocks/Events
- ↑ https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Building_blocks/Events
- ↑ https://www.w3schools.com/js/js_htmldom_eventlistener.asp
- ↑ https://www.w3schools.com/js/js_htmldom_eventlistener.asp
- ↑ https://www.w3schools.com/js/js_htmldom_eventlistener.asp
- ↑ "Event (computing)". Wikipedia. 2021-01-12. https://en.wikipedia.org/w/index.php?title=Event_(computing)&oldid=999891699.
- ↑ "JavaScript HTML DOM". www.w3schools.com. Retrieved 2019-09-15.
- ↑ https://www.w3schools.com/js/js_htmldom_events.asp
- ↑ "JavaScript/Event handling - Wikibooks, open books for an open world". en.wikibooks.org. Retrieved 2020-09-16.
- ↑ https://www.w3schools.com/js/js_htmldom_eventlistener.asp
- ↑ 17.0 17.1 17.2 17.3 "JavaScript Events". www.w3schools.com. Retrieved 2020-09-16.
- ↑ "JavaScript Events". www.w3schools.com. Retrieved 2020-09-16.
- ↑ 19.0 19.1 "JavaScript Events". www.w3schools.com. Retrieved 2020-09-16.
Lesson 5 - Conditions
[edit | edit source]This lesson introduces JavaScript conditions.
Objectives and Skills
[edit | edit source]Objectives and skills for this lesson include:[1]
- Evaluate expressions that use logical and comparison operators
- ==; !=; <, >; <=; >=; !; &&; ||
- Complete and debug decision statements
- if; else if; switch; nested if
- Complete and debug code that performs input validation
- Case; string comparisons; Not-A-Number (NaN)
Readings
[edit | edit source]- Wikipedia: Structured programming
- Wikipedia: Conditional (computer programming)
- Wikibooks: JavaScript/Control structures
- Mozilla: if...else
Multimedia
[edit | edit source]- YouTube: How to Create Conditions in JavaScript | Conditional Statements | JavaScript Tutorial
- YouTube: Introduction to Conditional Statements - p5.js Tutorial
- YouTube: JavaScript if - else Statement
- YouTube: How to use if/else conditions in JavaScript
- YouTube: JavaScript Tutorial for Beginners - 13 - Function and if statement
- YouTube: JavaScript Tutorial - Switch Statement
- YouTube: Switch - How to Use the JavaScript Switch Statement
- If Else Conditional Statements & Switch In JavaScript | JavaScript Tutorial For Beginners
Examples
[edit | edit source]- 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
[edit | edit source]Complete one of the following activities for each type of condition using external JavaScript code. Apply JavaScript best practices, including comments, indentations, naming conventions, and constants. Use input elements for input and respond to input or change events or add buttons and respond to click events. Use HTML elements for output. Use separate functions for each type of processing. Avoid global variables by passing parameters and returning results. Create test data to validate the accuracy of each program. Add comments at the top of the program and include references to any resources used.
If Conditions
[edit | edit source]- 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]
- 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.
- 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.
- 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.
- Create a program that helps the user determine what sock size to order based on their shoe size:
< 4 = extra small
4 to 6 = small
7 to 9 = medium
10 to 12 = large
13+ = extra large
Use if/else conditional statements to determine their selection and then display the results. Round half-sizes up to the next whole size. One option for rounding is to add 0.5 and then convert to an integer.[3]
Switch Conditions
[edit | edit source]- 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.
- 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.
- Create a program that helps the user determine what sock size to order based on their shoe size:
< 4 = extra small
4 to 6 = small
7 to 9 = medium
10 to 12 = large
13+ = extra large
Use switch conditional statements to determine their selection and then display the results. Round half-sizes up to the next whole size. One option for rounding is to add 0.5 and then convert to an integer.[4]
Input Validation
[edit | edit source]- Review Wikipedia: Is functions. Update one or more of the programs above to include input validation for all numeric input.
- Extend one or more of the programs above by adding structured exception handling statements (try-catch) to handle any runtime errors caused by the user entering invalid values for the input.
Lesson Summary
[edit | edit source]- 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.
- Break keyword is used to break down from the switch block. Once the match is found, and the associated code block is executed, the following cases are not being tested against the condition.[11]
- The switch statement may have an optional default case. It specifies the block of code that runs if there is no case match.[12]
- Conditional statements can be inside of other conditional statements, and can have multiple conditions to test.[13]
- When writing conditions based on equality, "==" is used rather than "=", which is the assignment operator.
Key Terms
[edit | edit source]- boolean
- A datatype that can only hold a value of either TRUE or FALSE.[14]
- break
- Keyword that breaks out of the switch block. This will stop the execution of inside the block.[15]
- comparison operators
- Comparison operators are used in logical statements to determine equality or difference between variables or values.[16]
- conditional statement
- It is a condition that has to be fulfilled (true) to perform an action.[17]
- default
- Keyword that specifies the code to run if there is no case match.[18]
- "else" statement
- The else statement is to specify a block of code to be executed if the same condition is false.[19]
- "else if" statement
- The else if statement specifies a new condition if the first condition is not met.[20]
- "if" statement
- The if statement executes a statement if a specified condition is true. If the condition is false, the code within the If statement is ignored, and the code immediately after will run.[21]
- logical operators
- Logical operators are used to determine the logic between variables or values.[22]
- nested if statement
- An if statement inside another if statement (multiple if statements).[23]
- switch
- Used to select one of many code blocks to be executed based on evaluation of a single expression.[24]
See Also
[edit | edit source]- 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
[edit | edit source]- ↑ Microsoft: Exam 98-382 Introduction to Programming Using JavaScript
- ↑ PythonLearn: Conditional Execution
- ↑ Wikibooks: Programming Fundamentals/Practice: Conditions
- ↑ Wikibooks: Programming Fundamentals/Practice: Conditions
- ↑ W3Schools: JavaScript if else and else if
- ↑ W3Schools: JavaScript if else and else i
- ↑ W3Schools: JavaScript if else and else i
- ↑ W3Schools: JavaScript if else and else i
- ↑ W3Schools: JavaScript switch Statement
- ↑ W3Schools: JavaScript switch Statement
- ↑ W3Schools: JavaScript switch Statement
- ↑ W3Schools: JavaScript switch Statement
- ↑ MDN | If... Else
- ↑ https://www.w3schools.com/js/js_booleans.asp
- ↑ https://www.w3schools.com/js/js_switch.asp
- ↑ https://www.w3schools.com/js/js_comparisons.asp
- ↑ https://www.w3schools.com/js/js_if_else.asp
- ↑ https://www.w3schools.com/js/js_switch.asp
- ↑ https://www.w3schools.com/js/js_if_else.asp
- ↑ https://www.w3schools.com/js/js_if_else.asp
- ↑ https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/if...else
- ↑ https://www.w3schools.com/js/js_comparisons.asp
- ↑ https://www.educba.com/nested-if-in-javascript/
- ↑ "JavaScript Switch Statement". www.w3schools.com. Retrieved 2019-09-27.
Lesson 6 - While Loops
[edit | edit source]This lesson introduces JavaScript while and do while loops.
Objectives and Skills
[edit | edit source]Objectives and skills for this lesson include:[1]
- Complete and debug loops
- for; while; do; break; continue
Readings
[edit | edit source]- Wikipedia: Control flow
- Wikibooks: JavaScript/Control structures
- Techdifferences: Difference Between while and do-while Loop
Multimedia
[edit | edit source]- YouTube: While/do while loop | JavaScript Full Tutorial
- YouTube: JavaScript Tutorial for Beginners - 11 - Loops
- YouTube: #16 While loop in JavaScript
- YouTube: freeCodeCamp.org While / Do While
- YouTube: JavaScript Tutorial For Beginners #16 - While Loops
- YouTube: JavaScript beginner tutorial 21 - do while loop
- YouTube: JavaScript Loops
- YouTube: 4.1: while and for Loops
Examples
[edit | edit source]- W3Schools: JavaScript While Loop
- W3Schools: JavaScript Do/While Loop
- Example Code
- DigitalOcean: While Loops
Activities
[edit | edit source]Complete one the following activities in each category of loop using external JavaScript code. Apply JavaScript best practices, including comments, indentations, naming conventions, and constants. Use input elements for input and respond to input or change events or add buttons and respond to click events. Use HTML elements for output. Use separate functions for each type of processing. Avoid global variables by passing parameters and returning results. Create test data to validate the accuracy of each program. Add comments at the top of the program and include references to any resources used.
While Loops
[edit | edit source]Complete the following using a while loop structure.
- 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
- 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.
- 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)
- Review MathsIsFun: Definition of Average. Create a program that asks the user to enter grade scores. Start by asking the user how many scores they would like to enter. Then request each score using an input element and add it to a total. Finally, calculate and display the average for the entered scores. In this approach, the loop action is performed by the user rather than by the code. Use hidden elements to keep track of the total and count.
Do While Loops
[edit | edit source]Complete the following using a do while loop structure.
- 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.
- 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.
- 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.
- Review Khan Academy: A guessing game. Write a program that allows the user to think of a number between 0 and 100, inclusive. Then have the program try to guess their number. Start at the midpoint (50) and ask the user if their number is (h)igher, (l)ower, or (e)qual to the guess using three buttons. If they indicate lower, guess the new midpoint (25). If they indicate higher, guess the new midpoint (75). Continue efficiently guessing higher or lower until they indicate equal, then print the number of guesses required to guess their number and end the program. In this approach, the loop action is performed by the user rather than by the code.
Lesson Summary
[edit | edit source]- 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
[edit | edit source]- Increment
- The increment operator (++) increments (adds one to) its operand and returns a value.[8]
- Decrement
- the Decrement operator (
--
) decrements (subtracts one from) its operand and returns a value.[9]
- do while loop
- This loop will execute the code block once, before checking if the condition is true, then it will repeat the loop as long as the condition is true.[10]
- Infinite loop
- A loop that theoretically runs forever.[11]
- Iteration
- It's a repetition of code or cycle, performed by a loop[12]
- while loop
- The while loop executes a block of code repeatedly as long as a specified condition is true.[13]
See Also
[edit | edit source]- 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
[edit | edit source]- ↑ Microsoft: Exam 98-382 Introduction to Programming Using JavaScript
- ↑ 2.0 2.1 MDNː Loops and iteration
- ↑ Wikipedia: Don't repeat yourself
- ↑ Craie-programmingː Coding repetition
- ↑ CSULBː CECS 174, Loops
- ↑ Wikipediaː Infinite loop
- ↑ "while - JavaScript | MDN". developer.mozilla.org. Retrieved 2021-02-28.
- ↑ "Increment (++)". MDN Web Docs. Retrieved 2020-09-29.
- ↑ "Decrement (--) - JavaScript | MDN". developer.mozilla.org. Retrieved 2023-02-26.
- ↑ "JavaScript for Loop". www.w3schools.com. Retrieved 2023-02-26.
- ↑ JavaScript.info: While and For
- ↑ MDN: Loops and Iteration
- ↑ W3Schools: JavaScript for loop
Lesson 7 - For Loops
[edit | edit source]This lesson introduces JavaScript for loops and nested loops.
Objectives and Skills
[edit | edit source]Objectives and skills for this lesson include:[1]
- Complete and debug loops
- for; while; do; break; continue
Readings
[edit | edit source]Multimedia
[edit | edit source]- YouTube: JavaScript Tutorial for Beginners - 28 - getElementsByTagName Part 2
- Youtube: For Loops | Javascript | Tutorial 23
- YouTube: #17 For Loop in JavaScript
- YouTube: For Loops - Beau teaches JavaScript
- YouTube: JavaScript Tutorial for Beginners - 12 - Loops Part 2
- YouTube: JavaScript Tutorials for Beginners - 9 - How to Code Nested For Loops with JavaScript
- Youtube: JavaScript Nested Loops
- YouTube: #18 While vs For Loop | Which to use and When?
- JavaScript Loops
Examples
[edit | edit source]- W3Schools: JavaScript For Loop
- W3Schools: JavaScript Break and Continue
- Programiz: Javascript For Loop Examples
- Example Code
- FreeCodeCamp: For Loops
Activities
[edit | edit source]Complete the following activities using external JavaScript code. Apply JavaScript best practices, including comments, indentations, naming conventions, and constants. Use input elements for input and respond to input or change events or add buttons and respond to click events. Use HTML elements for output. Use separate functions for each type of processing. Avoid global variables by passing parameters and returning results. Create test data to validate the accuracy of each program. Add comments at the top of the program and include references to any resources used.
For Loops
[edit | edit source]Complete the following using a for loop structure.
- 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
- 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.
- Review MathsIsFun: Pi. Write a program that uses the Nilakantha series to calculate Pi based on a given number of iterations entered by the user.
Nested Loops
[edit | edit source]Complete the following using a nested loop structure.
- Review MathsIsFun: 10x Printable Multiplication Table. Create a program that uses nested loops to generate a multiplication table. Rather than simply creating a 10 by 10 table, ask the user to enter the starting and ending values. Include row and column labels. For example, the output from 1 to 3 might look like:
1 2 3
1 1 2 3
2 2 4 6
3 3 6 9
The output from 3 to 5 might look like:
3 4 5
3 9 12 15
4 12 16 20
5 15 20 25
Lesson Summary
[edit | edit source]- 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
[edit | edit source]- break
- A statement used to jump out of a loop.[11]
- continue
- A statement where it breaks one iteration (in the loop), if a specified condition occurs, and continues with the next iteration in the loop.[12]
- for loop
- Loops repeatedly executes a block of code a specified number of times.[13]
- for/in loop
- loops through the properties of an object.[13]
- for/of loop
- loops through the values of an iterable data structures such as Arrays, Strings, Maps, NodeLists, and more.[13]
- loop counter
- A variable that controls how many iterations of a loop occurs. [14]
- nested loops
- A composition of loops is called a nested loop. The most common type of nested loops will be one loop inside another. The first loop is usually called the outer loop while the second loop is called the inner loop.[15]
See Also
[edit | edit source]- 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
[edit | edit source]- ↑ Microsoft: Exam 98-382 Introduction to Programming Using JavaScript
- ↑ 2.0 2.1 MDNː Loops and iteration
- ↑ Wikipedia: Don't repeat yourself
- ↑ Craie-programmingː Coding repetition
- ↑ CSULBː CECS 174, Loops
- ↑ Wikipediaː Infinite loop
- ↑ W3Schools: JavaScript For Loop
- ↑ W3Schools: JavaScript For Loop
- ↑ W3Schools: JavaScript For Loop
- ↑ FreeCodeCamp: JavaScript Loops Explained
- ↑ W3Schools: JavaScript break
- ↑ "JavaScript Break and Continue". www.w3schools.com. Retrieved 2020-10-06.
- ↑ 13.0 13.1 13.2 W3Schools: JavaScript for loop
- ↑ "For loop". Wikipedia. 2021-02-17. https://en.wikipedia.org/w/index.php?title=For_loop&oldid=1007384841.
- ↑ EXL Skills: JavaScript Nested Loops
Lesson 8 - Arrays
[edit | edit source]This lesson introduces JavaScript arrays.
Objectives and Skills
[edit | edit source]Objectives and skills for this lesson include:[1]
- Declare and use arrays
- Single-dimensional arrays; multi-dimensional arrays; iteration; initialization; define an array; sort and search an array; use push, pop, shift, and unshift methods; use the length property; access an array element;
Readings
[edit | edit source]Multimedia
[edit | edit source]- YouTube: JavaScript Tutorial for Beginners - 17 - Arrays
- YouTube: JavaScript Arrays with different data types
- YouTube: How to Create Arrays in JavaScript
- Youtube: JavaScript Tip: 7 Ways to Iterate Over an Array
- YouTube: Push, Pop, Unshift and Shift Array Methods
- YouTube: Multidimensional array tutorial
- YouTube: 7.2: Arrays and Loops - p5.js Tutorial
Examples
[edit | edit source]- 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
[edit | edit source]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.
- Extend any of the activities from JavaScript Programming/Loops to use an array to hold the information generated during processing (values only) and display the results from the array (add HTML formatting) after processing is complete.
Lesson Summary
[edit | edit source]- The first element of the array has an index of
0
. The second element has an index of1
. The last element has an index ofarrayName.length - 1
.[2] - JavaScript arrays are used to store multiple values in a single variable.[2]
- An array that has multiple arrays in it is called a multi-dimensional array. [2]
- Arrays are commonly used to loop across a set of elements.
- In JavaScript, an array is not actually an explicit data type, but a predefined object of elements. [3]
Key Terms
[edit | edit source]- 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]
- multi-dimensional array
- An array whose elements consist of other arrays.[9]
- pop() method
- This method removes the last element from an array.[10]
- push() method
- Is the easiest way to add a new element to an array.[2]
- array.reduce() method
- Runs a function on each array element to produce (reduce it to) a single value.[11]
- sort() method
- The sort() method sorts an array alphabetically. [12]
- filter() method
- The filter() method allows you to exclude array elements that match specific criterias. [13]
See Also
[edit | edit source]- 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
[edit | edit source]- ↑ Microsoft: Exam 98-382 Introduction to Programming Using JavaScript
- ↑ 2.0 2.1 2.2 2.3 2.4 https://www.dyn-web.com/javascript/arrays/multidimensional.php
- ↑ "Indexed collections - JavaScript | MDN". developer.mozilla.org. Retrieved 2021-03-16.
- ↑ https://www.w3schools.com/js/js_arrays.asp
- ↑ https://www.w3schools.com/js/js_array_methods.asp
- ↑ https://www.w3schools.com/jsref/jsref_indexof_array.asp
- ↑ https://www.w3schools.com/jsref/jsref_obj_array.asp
- ↑ https://www.w3schools.com/jsref/jsref_length_array.asp
- ↑ https://www.dyn-web.com/javascript/arrays/multidimensional.php
- ↑ "JavaScript Array Methods". www.w3schools.com. Retrieved 2020-10-13.
- ↑ "JavaScript Array Iteration Methods". www.w3schools.com. Retrieved 2021-03-11.
- ↑ https://www.w3schools.com/js/js_array_sort.asp
- ↑ https://sebhastian.com/javascript-filter-array/
Lesson 9 - Date and Time
[edit | edit source]This lesson introduces JavaScript objects using dates.
Objectives and Skills
[edit | edit source]Objectives and skills for this lesson include:[1]
- Complete and debug code that uses objects
- Properties; methods; instantiation; Date object; retrieve date and time parts; localize date format (MM/DD vs DD/MM); add and subtract dates
Readings
[edit | edit source]Multimedia
[edit | edit source]- YouTube: Date Objects
- YouTube: Display and Change the Time And Date With JavaScript
- YouTube: Date methods in JavaScript
- YouTube: Displaying the Current/Live Date & Time on a Web Page
- YouTube: JavaScript Programming Tutorial 48 - Using Dates and Unix Timestamps in JavaScript
- #16 How to use the JS Date object | JavaScript Full Tutorial
Examples
[edit | edit source]- 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
[edit | edit source]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.
- 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.
- 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.
- 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.
- 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.
- Use JavaScript Date.now() and loops to time two different ways to implement the same thing. For example, is it faster to use a local variable or update an HTML element on each loop iteration?
Lesson Summary
[edit | edit source]- The Date object is used to work with dates and times.[2]
- By default, JavaScript will use the browser's time zone and display a date as a full-text string.[3]
- Date objects are created with the new Date() constructor, which can take parameters: year, month, day, hours, minutes, seconds, milliseconds.[3]
- JavaScript stores dates as the number of milliseconds since Unix Epoch (January 01, 1970, 00:00:00 UTC).[3]
- The JavaScript Date object has a list of get methods that can be used to get date's information such as day, hours, minutes, etc.[4]
- The JavaScript Date object also has a list of set methods that can be used to set date's information in a Date object.[5]
- The "date" input type creates a drop-down in html.
- The timing events setTimeout() executes once and setInterval() executes function continously can be used to execute code at time interval.[6]
- A UNIX epoch time and JavaScript date are not the same. Unix epoch time is seconds Ince the Unix Epoch, whereas the JavaScript date is milliseconds. [7]
Key Terms
[edit | edit source]- epoch Time
- Epoch time or Unix time is a way to track time as a running total of seconds. This count starts at the Unix Epoch on January 1st, 1970 at UTC. Therefore, the Unix time stamp is merely the number of seconds between a particular date and the Unix Epoch.[8]
- ISO
- ISO is the International standard for the representation of dates and times. The ISO syntax is YYYY-MM-DD, and is the preferred JavaScript date format.[9]
- new date()
- Returns a new Date object that represents the current date and time.[10]
- prototype
- Allows you to add properties and methods to an object.[11]
- setInterval()
- A method calls a function or evaluates an expression at specified intervals (in milliseconds).[12]
- setTimeout()
- A method calls a function or evaluates an expression after a specified number of milliseconds.[13]
- UTC
- The Universal Coordinated Time (UTC) is the time set by the World Time Standard.[14]
See Also
[edit | edit source]- 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
[edit | edit source]- ↑ Microsoft: Exam 98-382 Introduction to Programming Using JavaScript
- ↑ W3Schools: JavaScript Date Reference
- ↑ 3.0 3.1 3.2 W3Schoolsː JavaScript Date Objects
- ↑ W3Schools: JavaScript Date Methods
- ↑ W3Schools: JavaScript Set Date Methods
- ↑ W3Schools: JavaScript Timing Events
- ↑ "Date - JavaScript | MDN". developer.mozilla.org. Retrieved 2021-03-26.
- ↑ Epoch & Unix Timestamp
- ↑ "JavaScript Date Formats". www.w3schools.com. Retrieved 2023-03-17.
- ↑ "Date JavaScript API". www.javascripture.com. Retrieved 2020-10-20.
- ↑ [1]
- ↑ [2]
- ↑ [3]
- ↑ W3Schools: Universal Coordinated Time
Lesson 10 - Objects
[edit | edit source]This lesson introduces JavaScript objects.
Objectives and Skills
[edit | edit source]Objectives and skills for this lesson include:[1]
- Complete and debug code that uses objects
- Properties; methods; instantiation; Date object; retrieve date and time parts; localize date format (MM/DD vs DD/MM); add and subtract dates
Readings
[edit | edit source]Multimedia
[edit | edit source]- YouTube: JavaScript Tutorial for Beginners - 18 - Objects
- YouTube: JavaScript Tutorial for Beginners - 19 - Objects Part 2
- YouTube: JavaScript Tutorial for Beginners - 20 - Objects Part 3
- YouTube: JavaScript Tutorial for Beginners - 21 - Objects Part 4
- YouTube: JavaScript Tutorial for Beginners - 22 - String Object
- YouTube: JavaScript Tutorial for Beginners - 51 - More on Objects
- YouTube: JavaScript this Keyword
- Javascript Objects Explained | Javascript Objects Tutorial
Examples
[edit | edit source]- W3Schools: JavaScript Objects
- W3Schools: JavaScript Object Properties
- W3Schools: JavaScript Object Methods
- W3Schools: JavaScript Object Constructors
- Example Code
Activities
[edit | edit source]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.
- 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. - 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.
- 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. - 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.
- Extend the program above, allowing the user to choose either APA or MLA format, and display the selected format for each book. List the books in alphabetical order.
Lesson Summary
[edit | edit source]- An object is a set of properties or methods.[4] Each object holds related data.[5]
- Objects are written in the name:value pair format.[4] Each pair must be separated by a comma. [5]
- Object properties may be accessed using the dot notation or the bracket notation. [6]
- Object properties can be a wide array of data types, such as arrays or even other objects.
- In JavaScript, almost everything is an object. Only primitive date types, such as number, string, and Boolean, are not objects.[7]
Key Terms
[edit | edit source]- method
- An action that an object can perform. A method is a function stored as a property, specific to that object. [8]
- object
- In JavaScript, almost "everything" is an object. Booleans, numbers, strings, dates, maths, regular expressions, arrays functions, and objects. All values, except primitive values, are objects.[9]
- property
- A property is a value associated with a JavaScript object.[10]
constructor
A constructor is a function that creates an object using the given inputs.
- this
- Refers to the owner of a function.[11]
See Also
[edit | edit source]- 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
[edit | edit source]- ↑ Microsoft: Exam 98-382 Introduction to Programming Using JavaScript
- ↑ EasyBib:APA Book Reference
- ↑ EasyBib:MLA Book Reference
- ↑ 4.0 4.1 W3Schoolsː JavaScript Objects
- ↑ 5.0 5.1 MDNː JavaScript object basics
- ↑ MDNː Property accessors
- ↑ https://www.w3schools.com/js/js_object_definition.asp
- ↑ https://www.w3schools.com/js/js_objects.asp
- ↑ https://www.w3schools.com/js/js_object_definition.asp
- ↑ https://www.geeksforgeeks.org/javascript-object-properties
- ↑ https://www.w3schools.com/js/js_objects.asp
Lesson 11 - DOM and BOM
[edit | edit source]This lesson introduces the JavaScript Document Object Model (DOM) and Browser Object Model (BOM).
Objectives and Skills
[edit | edit source]Objectives and skills for this lesson include:[1]
- Identify and construct the Document Object Model (DOM) tree
- window; document; body; other HTML elements
- Complete and debug code that outputs to an HTML document
- innerHTML; document.write
- Complete and debug code that interacts with the Browser Object Model (BOM)
- Manage state; display dialogs; determine screen size
Readings
[edit | edit source]- Wikipedia: Document Object Model
- Wikipedia: Browser Object Model
- Wikibooks: JavaScript/Introduction to the Document Object Model (DOM)
Multimedia
[edit | edit source]- YouTube: JavaScript Tutorial for Beginners - 25 - Document Object Model
- YouTube: JavaScript Tutorial for Beginners - 40 - Traversing the DOM
- YouTube: JavaScript Tutorial for Beginners - 41 - Traversing the DOM Part 2
- YouTube: JavaScript Tutorial for Beginners - 42 - Traversing the DOM Part 3
- YouTube: An Introduction to the DOM (Document Object Model) in JavaScript
- YouTube: Document Object Model Tutorial
- Youtube: Javascript DOM Manipulation
- YouTube: JavaScript Programming Tutorial 91 - Intro to the DOM
- JavaScript DOM Manipulation – Full Course for Beginners
Examples
[edit | edit source]- 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
[edit | edit source]elizabethannchazarretaarias/ssn0730/dob;6/14/1967/ recovery /over all fraud takan over all my profile under user made by dav/ and vijay/ stop and finde in all profile users/found at 3917 melliit ave ft.worth tx/and outher places under apple smart sofewere stolan alter and made payouts under apple and smart devices//and androuids/p;aces only to put a bug under my name and all recovery of stolan info made by contacts ir others ways smart devices aplace set to steal money over my complance lawsuites used only to larrer li8ve me a lone home less and without anyone ever bing truth i hope all fell better now ihave nowere to live or go/what hate over every hatefull person who whant this man who can have him and can live me alone ive never seen so much upseth with him and hate overme guess what all made under eval julicole and meditmolena and dallas hope oneday all can fell what i had to go thourgth in made me suffer killoff my family take awy` eeverty think i love neday may god be your judagedmebt and if you see /for icant keep bing around so much hatefull/ live me alone ihad to see only all in make me look like idont matter this provan evryday i get it now with same statemwent live me aloneomplete the following activities using external JavaScript code. Apply JavaScript best practices, including comments, indentations, naming conventions, and constants. Use input elements for input and respond to input or change events, add buttons and respond to click events, or set a timer interval and respond to interval events. Use HTML elements for output. Use separate functions for each type of processing. Avoid global variables by passing parameters and returning results. Create test data to validate the accuracy of each program. Add comments at the top of the program and include references to any resources used.
- Create JavaScript code to display all tags in the current HTML document using document.getElementsByTagName("*").
- 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.
- Create JavaScript code to display the current window size, screen size, and location information. Use the resize event to update the display whenever the window size changes.
Lesson Summary
[edit | edit source]- The Document Object Model (DOM) defines a standard for accessing documents.[2]
- The Browser Object Model (BOM) allows JavaScript to "talk to" the browser.[3]
- In the HTML DOM, the Element object represents an HTML element, like P, DIV, A, TABLE, or any other HTML element.[4]
- DOM is frequently depicted similarly to a tree, where the child nodes branch downwards off their parents.
- Parent-child relationships within the DOM can be used to target document elements. It is possible to move (traverse) from parent to child (downwards), from child to parent (upwards), and from sibling to sibling (sideways).[5]
- HTML DOM is a standard for how to get, change, add, or delete HTML elements.[6]
- DOM is essential for allowing webpages to change shape in response to user activity.
- The BOM allows JavaScript to access several peices of information about a browser (with some limits for security) including: history, screen size, location, and cookies. [7]
Key Terms
[edit | edit source]- Browser Object Model (BOM)
- The API of the browser that allows JavaScript to communicate with the browser.[8]
- Document Object Model (DOM)
- The data representation of the objects that comprise the structure and content of a document on the web.[9]
- node
- An HTML element. The "DOM" is a tree structure that represents the HTML of the website, and every HTML element is a "node". More specifically, "Node" is an interface that is implemented by multiple objects.[10]
- Node Relationships
- The nodes in the node tree have a hierarchical relationship to each other. The terms parent, child, and sibling are used to describe the relationships.[11]
See Also
[edit | edit source]- 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
[edit | edit source]- ↑ Microsoft: Exam 98-382 Introduction to Programming Using JavaScript
- ↑ w3schools: JavaScript HTML DOM<
- ↑ w3schools: JavaScript Window
- ↑ w3schools: HTML DOM Elemenets
- ↑ EJ Mediaː JavaScript Tutorial for Beginners - 40 - Traversing the DOM
- ↑ w3schools: HTML DOM
- ↑ "JavaScript Window". www.w3schools.com. Retrieved 2021-04-02.
- ↑ w3schools: JavaScript Window
- ↑ MDN: DOM Introduction
- ↑ "JavaScript DOM Nodes". www.w3schools.com. Retrieved 2023-04-08.
- ↑ "JavaScript DOM Navigation". www.w3schools.com. Retrieved 2023-04-08.
Lesson 12 - Dynamic HTML
[edit | edit source]This lesson introduces dynamic HTML.
Objectives and Skills
[edit | edit source]Objectives and skills for this lesson include:[1]
- Complete and debug code that locates, modifies, and adds HTML elements and attributes
- getElementByld; getElementsByTagName; getElementsByClassName; setAttribute; createElement
- createElement, createTextNode, appendChild
Readings
[edit | edit source]Multimedia
[edit | edit source]- YouTube: JavaScript Tutorial for Beginners - 36 - Creating a new element
- YouTube: JavaScript Tutorial for Beginners - 37 - Creating a new element Part 2
- YouTube: JavaScript Tutorial for Beginners - 38 - Remove element
- YouTube: JavaScript Tutorial for Beginners - 39 - Create attribute
- YouTube: JavaScript Create HTML Element: How to dynamically add tags to your pages
- YouTube: JavaScript Dynamic Welcoming Message
- YouTube: JavaScript Programming Tutorial 99 - Dynamically Adding Nodes
Examples
[edit | edit source]- 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
[edit | edit source]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.
- Extend any of the activities from JavaScript Programming/Arrays to use an array to hold the information generated during processing and display the results from the array using dynamic HTML to create and append HTML elements after processing is complete.
Lesson Summary
[edit | edit source]- To dynamically change your HTML with JavaScript, you need to fully understand how to traverse the node tree and the relationship between nodes.[2]
- Each HTML element node, except the root element node, has a parent node.[3]
- Text is the value of the text node. The text node has to be created and appended to the element. [4]
- Things DHTML is used for includes animating content, roll-over and dropdown menus, and verifying and responding to forms without using the server. [5]
- To add a new element to the HTML DOM, you must create the element (element node) first, and then append it to an existing element.[4]
- Creating strings and consectively adding HTML elements to them is a a common method of creating new elements to HTML using javascript.
Key Terms
[edit | edit source]- dynamic HTML
- Dynamic HTML (DHTML) is based on properties of the HTML, JavaScript, CSS, and DOM which helps in making dynamic content. DHTML makes use of Dynamic object model to make changes in settings and also in properties and methods.[6]
- node
- Every Element in the HTML document is a node [7]
- NodeList object
- A NodeList object is a list (collection) of nodes extracted from a document.[8]
- node relationships
- The nodes in the node tree have a hierarchical relationship to each other. The terms parent, child, and sibling are used to describe the relationships. [9]
See Also
[edit | edit source]- 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
[edit | edit source]- ↑ Microsoft: Exam 98-382 Introduction to Programming Using JavaScript
- ↑ https://www.w3schools.com/js/js_htmldom_navigation.asp
- ↑ W3Schoolsː JavaScript HTML DOM Navigation
- ↑ 4.0 4.1 W3Schoolsː JavaScript HTML DOM Elements (Nodes)
- ↑ "Dynamic HTML". Wikipedia. 2021-04-03. https://en.wikipedia.org/w/index.php?title=Dynamic_HTML&oldid=1015848128.
- ↑ https://www.geeksforgeeks.org/dhtml-introduction/
- ↑ https://www.w3.org/2003/01/dom2-javadoc/org/w3c/dom/Node.html
- ↑ https://www.w3schools.com/js/js_htmldom_nodelist.asp
- ↑ https://www.w3schools.com/js/js_htmldom_navigation.asp
Lesson 13 - Forms and Security
[edit | edit source]This lesson introduces JavaScript form processing and security.
Objectives and Skills
[edit | edit source]Objectives and skills for this lesson include:[1]
- Complete and debug code that retrieves input from forms and sets form field values
- Retrieve form values; identify the DOM path; get values from different types of elements; prepopulate values; mask values
- Describe the form submission process
- onsubmit; post versus get; potential targets for submission
- Implement exception handling
- try; catch; finally
Readings
[edit | edit source]- Wikipedia: Form (HTML)
- Wikipedia: Data validation
- Wikibooks: JavaScript/Forms
- Wikipedia: Web application security
- Wikipedia: Exception handling
- Input tag Definition and Usage
Multimedia
[edit | edit source]- Youtube: The "submit" event on forms in JavaScript
- YouTube: JavaScript Form Validation
- YouTube: JavaScript Tutorial for Beginners - 43 - Form Validation Part 1
- YouTube: JavaScript Tutorial for Beginners - 44 - Form Validation Part 2
- YouTube: JavaScript Tutorial for Beginners - 45 - Form Validation Part 3
- YouTube: JavaScript Tutorial for Beginners - 46 - Form Validation Part 4
- YouTube: JavaScript Tutorial for Beginners - 47 - Form Validation Part 5
- YouTube: Learn Regular Expressions In 20 Minutes
- YouTube: Writing Secure JavaScript
- JavaScript Form Validation
- Youtube: Creating Contact Page with JS
Examples
[edit | edit source]- W3Schools: JavaScript Forms
- W3Schools: HTML Form Attributes
- W3Schools: JavaScript Validation API
- W3Schools: Enctype in Form tag
- W3Schools: JavaScript RegExp Reference
- Example Code
Activities
[edit | edit source]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.
- 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.
- 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.
- 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.
- Include two buttons, one labeled GET and the other labeled POST. Use JavaScript to change the form request method based on the button selected. Use https://postman-echo.com to echo submitted requests and compare the differences in data transmission format for the two types of requests.
Lesson Summary
[edit | edit source]- 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
[edit | edit source]- checkValidity()
- This input element method returns true if the element contains valid data according to the rules you have specified in the input field.[2]
- Client-Side Form Validation
- An initial check that happens in the browser and helps ensure users fill out the form using correct data formats. Error messages are displayed if corrections are needed.[3]
- GET Method
- Used to request data from a specified resource. The query string (name/value pairs) is sent in the URL of a GET request.[4]
- pattern
- HTML <input> attribute that specifies a regular expression that the <input> element's value is checked against on form submission.[5]
- POST Method
- Used to send data to a server to create/update a resource. The data sent to the server is stored in the request body of the HTTP request.[4]
- reportValidity()
- Runs the checkValidity method on the element's child controls. Those child elements which do not satisfy their validation constraints are reported to the user.[6]
- required
- HTML <input> attribute that when present, will specify that an input field must be filled out before submitting the form.[7]
- Server-Side Form Validation
- A validation that checks the data sent to the server and ensures that incorrect or malicious data is rejected.[3]
- setCustomValidity()
- This method sets the custom validity message for the selection element to the specified message. To reset the validity use an empty string as a parameter.[8]
- validityState()
- The ValidityState returns an object containing the errors detected via HTML constraint validation.[9]
See Also
[edit | edit source]- 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
[edit | edit source]- ↑ Microsoft: Exam 98-382 Introduction to Programming Using JavaScript
- ↑ https://www.w3schools.com/js/js_validation_api.asp
- ↑ 3.0 3.1 MDNː Form data validation
- ↑ 4.0 4.1 "HTTP Methods GET vs POST". www.w3schools.com. Retrieved 2023-04-22.
- ↑ https://www.w3schools.com/tags/att_input_pattern.asp
- ↑ https://developer.mozilla.org/en-US/docs/Web/API/HTMLFormElement/reportValidity
- ↑ https://www.w3schools.com/tags/att_input_required.asp
- ↑ https://developer.mozilla.org/en-US/docs/Web/API/HTMLSelectElement/setCustomValidity
- ↑ https://developer.mozilla.org/en-US/docs/Web/API/ValidityState
Lesson 14 - AJAX and JSON
[edit | edit source]This lesson introduces AJAX and JSON.
Objectives and Skills
[edit | edit source]Objectives and skills for this lesson include:
- Send and receive JSON data using AJAX
Readings
[edit | edit source]- Wikipedia: AJAX
- Wikipedia: JSON
- Wikibooks: JavaScript/XMLHttpRequest
- Wikibooks: JavaScript/Handling JSON
Multimedia
[edit | edit source]- YouTube: JSON and AJAX Tutorial: With Real Examples
- YouTube: JSON Crash Course
- YouTube: Learn JSON - Full Crash Course for Beginners
- AJAX - Beau teaches JavaScript
Examples
[edit | edit source]Activities
[edit | edit source]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.
- 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.
- 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.
- Optional: See Node.js REST API for information and examples on how to set up your own test JavaScript web server.
Lesson Summary
[edit | edit source]Additional items will be contributed by course participants
- JavaScript Object Notation or JSON is a universal data structure used to exchange information between multiple engines, languages, and servers. [1]
- JSON is a large string that stores literals, and has its own formatting and syntax.
- AJAX, or Asynchronous Javascript and XML, is a method for javascript to communicate with external webpages and/or servers.
- Using AJAX allows web developers to update their webpages without having to refresh or redirect the user to another page.
- GET and POST are the 2 main methods, being used to request and send data to servers, respectively.
Key Terms
[edit | edit source]- AJAX (Asynchronous JavaScript and XML)
- With AJAX, web applications can send and retrieve data from a server asynchronously (in the background) without interfering with the display and behavior of the existing page.[2]
- Data Interchange Format
- A data-interchange format is a text format which is used to interchange or exchange data between different platforms and operating systems. JSON is the most popular and lightweight data-interchange format for web applications.[3]
- GET
- GET is used to request data from a specified resource. GET is one of the most common HTTP methods (and the default method).[4]
- JSON
- JSON is text, written using JavaScript object notation.[5]
- onReadyStateChange
- It is an event handler that is called whenever the readyState attribute changes.[6]
- POST
- POST is used to send data to a server to create/update a resource. The data sent to the server with POST is stored in the request body of the HTTP request.[7]
- XMLHttpRequest
- The XMLHttpRequest object is used to interact with the server (get or post data). This enables a Web page to update just part of a page without disrupting what the user is doing.[8]
See Also
[edit | edit source]- 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
[edit | edit source]- ↑ JSON.org
- ↑ https://en.wikipedia.org/wiki/Ajax_(programming)
- ↑ https://en.wikipedia.org/wiki/Ajax_(programming)
- ↑ https://www.tutorialrepublic.com/javascript-tutorial/javascript-json-parsing.php
- ↑ https://www.w3schools.com/js/js_json_intro.asp
- ↑ https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/onreadystatechange
- ↑ https://www.w3schools.com/tags/ref_httpmethods.asp
- ↑ https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest
Lesson 15 - Libraries and Frameworks
[edit | edit source]This lesson introduces JavaScript libraries and frameworks.
Objectives and Skills
[edit | edit source]Objectives and skills for this lesson include:
- Understand the advantages and disadvantages of using JavaScript libraries and frameworks
- Recognize currently popular JavaScript libraries and frameworks
Readings
[edit | edit source]- Wikipedia: JavaScript library
- Wikipedia: JavaScript framework
- Wikipedia: Comparison of JavaScript frameworks
Multimedia
[edit | edit source]- YouTube: JavaScript Tutorial For Beginners #45 - JavaScript Libraries
- YouTube: What is a JavaScript Framework?
- YouTube: Choosing Your JavaScript Framework
- What is the difference between a framework and a library?
Examples
[edit | edit source]- W3Schools: jQuery
- W3Schools: Angular
- W3Schools: React
- W3Schools: W3.JS
- Vue.js: Guide
- W3schools: Bootstrap: getting started
Activities
[edit | edit source]- List advantages and disadvantages of using JavaScript libraries and frameworks.
- Research currently popular JavaScript libraries and frameworks. Consider different source approaches, including market share, industry recommendations, GitHub usage, and job search listings.
Lesson Summary
[edit | edit source]- Web frameworks provide a standard way to build and deploy web applications on the World Wide Web.[1]
- A library provides a set of helper functions/objects/modules which your application code calls for specific functionality.[2]
Key Terms
[edit | edit source]- term
- definition
- Library
- Collection of functions that are used to reuse and simplify coding.[3]
- Framework
- A web application framework is a software framework that is designed to support the development of dynamic websites, Web applications and Web services. The framework aims to alleviate the overhead associated with common activities used in Web development. For example, many frameworks provide libraries for database access, templating frameworks and session management, and often promote code reuse.[1]
See Also
[edit | edit source]- 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
[edit | edit source]Lesson 16 - Node.js REST API
[edit | edit source]This lesson introduces Node.js, Express.js and REST APIs.
Objectives and Skills
[edit | edit source]Objectives and skills for this lesson include:
- Understand Node.js concepts
- Understand Express.js concepts
- Use Node.js and Express.js to implement a simple REST API
Readings
[edit | edit source]Multimedia
[edit | edit source]Examples
[edit | edit source]Activities
[edit | edit source]- 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
- 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
- Create a new folder for your REST server application. In that folder, run the following command to generate an Express.js template:
- 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
[edit | edit source]- Bullet points
Key Terms
[edit | edit source]- term
- definition