SlideShare a Scribd company logo
1 of 59
Chapter 2
Murach's JavaScript and jQuery (3rd Ed.)
© 2017, Mike Murach & Associates, Inc.
Getting started
with JavaScript
C2, Slide 1
Objectives
Murach's JavaScript and jQuery (3rd Ed.)
© 2017, Mike Murach & Associates, Inc.
Applied
1. Given the specifications for a JavaScript application that requires
only the skills that you’ve learned so far, code, test, and debug the
application.
Knowledge
1. Describe two ways to include JavaScript in the head of an HTML
document.
2. Describe how JavaScript can be included in the body of an HTML
document.
3. Describe how case-sensitivity, semicolons, and whitespace relate to
the syntax for a JavaScript statement.
4. List the primary rules for creating a JavaScript identifier.
5. Describe the use of JavaScript comments, including “commenting
out” portions of JavaScript code.
C2, Slide 2
Objectives (continued)
Murach's JavaScript and jQuery (3rd Ed.)
© 2017, Mike Murach & Associates, Inc.
6. Describe the three primitive data types used in JavaScript: numeric,
string, and Boolean.
7. Describe the use of variable declarations and assignment statements
with numeric, string, and Boolean data.
8. Describe the use of the arithmetic operators and the rules for
evaluating an arithmetic expression, including order of precedence
and the use of parentheses.
9. Describe the use of the + operator and the n escape sequence when
working with strings.
10.Describe the syntax for referring to a method or property of an
object.
11.Describe the use of the alert(), prompt(), parseInt(), parseFloat(),
write(), and writeln() methods.
C2, Slide 3
Two attributes of the script element
Murach's JavaScript and jQuery (3rd Ed.)
© 2017, Mike Murach & Associates, Inc. C2, Slide 4
src
type
A script element in the head section
that loads an external JavaScript file
<script src="calculate_mpg.js"></script>
A script element that embeds JavaScript
in the head section
Murach's JavaScript and jQuery (3rd Ed.)
© 2017, Mike Murach & Associates, Inc. C2, Slide 5
<head>
...
<script>
alert("The Calculate MPG application");
var miles = prompt("Enter miles driven");
miles = parseFloat(miles);
var gallons =
prompt("Enter gallons of gas used");
gallons = parseFloat(gallons);
var mpg = miles/gallons;
mpg = parseInt(mpg);
alert("Miles per gallon = " + mpg);
</script>
</head>
Terms
Murach's JavaScript and jQuery (3rd Ed.)
© 2017, Mike Murach & Associates, Inc.
 external JavaScript file
 embedded JavaScript
C2, Slide 6
JavaScript in the body of an HTML document
Murach's JavaScript and jQuery (3rd Ed.)
© 2017, Mike Murach & Associates, Inc. C2, Slide 7
<p>
<script>
var today = new Date();
document.write("Current date: ");
document.write(today.toDateString());
</script>
</p>
<p>&copy;&nbsp;
<script>
var today = new Date();
document.write( today.getFullYear() );
</script>
, San Joaquin Valley Town Hall
</p>
The result of the JavaScript in a web browser
Murach's JavaScript and jQuery (3rd Ed.)
© 2017, Mike Murach & Associates, Inc. C2, Slide 8
A noscript element in the body
of an HTML document
Murach's JavaScript and jQuery (3rd Ed.)
© 2017, Mike Murach & Associates, Inc. C2, Slide 9
<p>&copy;&nbsp;
<script>
var today = new Date();
document.write( today.getFullYear() );
</script>
<noscript>2017</noscript>
, San Joaquin Valley Town Hall
</p>
A noscript element at the start
of an HTML document
Murach's JavaScript and jQuery (3rd Ed.)
© 2017, Mike Murach & Associates, Inc. C2, Slide 10
<h2>
<noscript>
To get the most from this website,
please enable JavaScript.
</noscript>
</h2>
A block of JavaScript code
Murach's JavaScript and jQuery (3rd Ed.)
© 2017, Mike Murach & Associates, Inc. C2, Slide 11
var joinList = function () {
var emailAddress1 = $("email_address1").value;
var emailAddress2 = $("email_address2").value;
if (emailAddress1 == "") {
alert("Email Address is required.");
} else if (emailAddress2 == "") {
alert("Second Email Address is required.");
} else if (emailAddress1 !== emailAddress2) {
alert("Second Email entry must equal first
entry.");
} else if ($("first_name").value == "") {
alert("First Name is required.");
} else {
$("email_form").submit();
}
}
The basic syntax rules for JavaScript
Murach's JavaScript and jQuery (3rd Ed.)
© 2017, Mike Murach & Associates, Inc.
 JavaScript is case-sensitive.
 Each JavaScript statement ends with a semicolon.
 JavaScript ignores extra whitespace within statements.
C2, Slide 12
How to split a statement over two or more lines
Murach's JavaScript and jQuery (3rd Ed.)
© 2017, Mike Murach & Associates, Inc. C2, Slide 13
 Split a statement after:
an arithmetic or relational operator like +, -, *, /, =, ==, >, or <
an opening brace ( { ), bracket ( [ ), or parenthesis
a closing brace ( } )
 Do not split a statement after:
an identifier, a value, or the return keyword
a closing bracket ( ] ) or parenthesis
Rules for creating identifiers
Murach's JavaScript and jQuery (3rd Ed.)
© 2017, Mike Murach & Associates, Inc. C2, Slide 14
 Identifiers can only contain letters, numbers, the underscore, and
the dollar sign.
 Identifiers can’t start with a number.
 Identifiers are case-sensitive.
 Identifiers can be any length.
 Identifiers can’t be the same as reserved words.
 Avoid using global properties and methods as identifiers.
Valid identifiers in JavaScript
Murach's JavaScript and jQuery (3rd Ed.)
© 2017, Mike Murach & Associates, Inc.
subtotal
index_1
$
taxRate
calculate_click
$log
C2, Slide 15
Camel casing versus underscore notation
Murach's JavaScript and jQuery (3rd Ed.)
© 2017, Mike Murach & Associates, Inc. C2, Slide 16
taxRate tax_rate
calculateClick calculate_click
emailAddress email_address
futureValue future_value
Naming recommendations for identifiers
Murach's JavaScript and jQuery (3rd Ed.)
© 2017, Mike Murach & Associates, Inc. C2, Slide 17
 Use meaningful names. That way, your identifiers aren’t likely to
be reserved words or global properties.
 Be consistent: Either use camel casing (taxRate) or underscores
(tax_rate) to identify the words within the variables in your
scripts.
 If you’re using underscore notation, use lowercase for all letters.
JavaScript code with the comments highlighted
Murach's JavaScript and jQuery (3rd Ed.)
© 2017, Mike Murach & Associates, Inc. C2, Slide 18
/* this application validates a user's entries for
joining our email list
*/
var $ = function(id) { // the $ function
return document.getElementById(id);
}
// this function gets and validates the user entries
var joinList = function() {
var emailAddress1 = $("email_address1").value;
var emailAddress2 = $("email_address2").value;
var firstName = $("first_name").value;
var isValid = true;
// validate the first entry
if (emailAddress1 == "") {
$("email_address1_error").firstChild.nodeValue =
"This field is required.";
isValid = false; // set valid switch to off
} else {
$("email_address1_error").firstChild.nodeValue = "";
}
// validate the second entry
...
...
};
The basic syntax rules for comments
Murach's JavaScript and jQuery (3rd Ed.)
© 2017, Mike Murach & Associates, Inc. C2, Slide 19
 Block comments begin with /* and end with */.
 Single-line comments begin with two forward slashes and
continue to the end of the line.
Guidelines for using comments
 Use comments to describe portions of code that are hard to
understand.
 Use comments to disable portions of code that you don’t want to
test.
 Don’t use comments unnecessarily.
Terms
Murach's JavaScript and jQuery (3rd Ed.)
© 2017, Mike Murach & Associates, Inc.
 statement
 whitespace
 identifier
 camel casing
 comment
 comment out
C2, Slide 20
JavaScript’s primitive data types
Murach's JavaScript and jQuery (3rd Ed.)
© 2017, Mike Murach & Associates, Inc. C2, Slide 21
 Number
 String
 Boolean
Examples of number values
Murach's JavaScript and jQuery (3rd Ed.)
© 2017, Mike Murach & Associates, Inc. C2, Slide 22
15 // an integer
-21 // a negative integer
21.5 // a decimal value
-124.82 // a negative decimal value
-3.7e-9 // floating-point notation for -0.0000000037
The number data type
 A number value can be an integer or a decimal value.
 In JavaScript, decimal values are stored as floating-point numbers.
 If a result is stored in a number data type that is larger or smaller
than the data type can store, it will be stored as the value Infinity
or -Infinity.
Examples of string values
Murach's JavaScript and jQuery (3rd Ed.)
© 2017, Mike Murach & Associates, Inc. C2, Slide 23
"JavaScript" // a string with double quotes
'String Data' // a string with single quotes
"" // an empty string
The string data type
 A string value is surrounded by double quotes or single quotes.
The string must start and end with the same type of quotation
mark.
 An empty string is a string that contains no characters. It is
entered by typing two quotation marks with nothing between
them.
The two Boolean values
Murach's JavaScript and jQuery (3rd Ed.)
© 2017, Mike Murach & Associates, Inc. C2, Slide 24
true // equivalent to true, yes, or on
false // equivalent to false, no, or off
The Boolean data type
 A Boolean value can be true or false. Boolean values are often
used in conditional statements.
How to declare and assign a value to a variable
in two statements
Murach's JavaScript and jQuery (3rd Ed.)
© 2017, Mike Murach & Associates, Inc. C2, Slide 25
Syntax
var variableName;
variableName = value;
Examples
var counter; // declaration statement;
// value is undefined
counter = 1; // assignment statement;
// value is 1
var sum, average; // declares two variables
sum = 0, average = 0; // assigns values to two
// variables
How to declare and assign a value to a variable
in one statement
Murach's JavaScript and jQuery (3rd Ed.)
© 2017, Mike Murach & Associates, Inc. C2, Slide 26
Syntax
var variableName = value;
Examples
var count = 1; // integer value of 1
var subtotal = 74.95; // decimal value of 74.95
var name = "Joseph"; // string value of "Joseph"
var email = ""; // empty string
var isValid = false; // Boolean value of false
var total = subtotal; // assigns value of
subtotal variable
var x = 0, y = 0; // declares and assigns
values to 2 variables
Terms
Murach's JavaScript and jQuery (3rd Ed.)
© 2017, Mike Murach & Associates, Inc. C2, Slide 27
 variable
 declare a variable
 assignment statement
 assignment operator
 literal value
 literal
 string literal
 numeric literal
JavaScript’s arithmetic operators
Murach's JavaScript and jQuery (3rd Ed.)
© 2017, Mike Murach & Associates, Inc. C2, Slide 28
Operator Name Description
+ Addition Adds two operands.
- Subtraction Subtracts the right operand from the
left operand.
* Multiplication Multiplies two operands.
/ Division Divides the right operand into the left
operand. The result is always a
floating-point number.
% Modulus Divides the right operand into the left
operand and returns the remainder.
++ Increment Adds 1 to the operand.
-- Decrement Subtracts 1 from the operand.
The order of precedence
for arithmetic expressions
Murach's JavaScript and jQuery (3rd Ed.)
© 2017, Mike Murach & Associates, Inc. C2, Slide 29
Order Operators Direction Description
1 ++ Left to right Increment operator
2 -- Left to right Decrement operator
3 * / % Left to right Multiplication, division,
modulus
4 + - Left to right Addition, subtraction
Examples of simple arithmetic expressions
Murach's JavaScript and jQuery (3rd Ed.)
© 2017, Mike Murach & Associates, Inc. C2, Slide 30
Example Result
5 + 7 12
5 - 12 -7
6 * 7 42
13 / 4 3.25
13 % 4 1
counter++ counter = counter + 1
counter-- counter = counter – 1
3 + 4 * 5 23 (the multiplication is done first)
(3 + 4) * 5 35 (the addition is done first)
13 % 4 + 9 10 (the modulus is done first)
13 % (4 + 9) 0 (the addition is done first)
Code that calculates sales tax
Murach's JavaScript and jQuery (3rd Ed.)
© 2017, Mike Murach & Associates, Inc. C2, Slide 31
var subtotal = 200;
var taxPercent = .05;
var taxAmount = subtotal * taxPercent; // 10
var total = subtotal + taxAmount; // 210
Code that calculates the perimeter of a rectangle
var width = 4.25;
var length = 8.5;
var perimeter = (2 * width) + (2 * length)
// (8.5 + 17) = 25.5
The most useful compound assignment operators
Murach's JavaScript and jQuery (3rd Ed.)
© 2017, Mike Murach & Associates, Inc. C2, Slide 32
Operator Description
+= Adds the result of the expression to the variable.
-= Subtracts the result of the expression from the
variable.
*= Multiplies the variable value by the result of the
expression.
Statements with compound assignment operators
var subtotal = 74.95;
subtotal += 20.00; // subtotal = 94.95
var counter = 10;
counter -= 1; // counter = 9
var price = 100;
price *= .8; // price = 80
Three ways to increment a counter variable by 1
Murach's JavaScript and jQuery (3rd Ed.)
© 2017, Mike Murach & Associates, Inc. C2, Slide 33
var counter = 1; // counter = 1
counter = counter + 1; // counter now = 2
counter += 1; // counter now = 3
counter++; // counter now = 4
A floating-point result that isn’t precise
Murach's JavaScript and jQuery (3rd Ed.)
© 2017, Mike Murach & Associates, Inc. C2, Slide 34
var subtotal = 74.95; // subtotal = 74.95
var salesTax = subtotal * .1; // salesTax =
7.495000000000001
A problem with some arithmetic operations
 When you do some types of arithmetic operations with decimal
values, the results aren’t always precise. That’s because decimal
values are stored internally as floating-point numbers.
 The primary problem with this is that an equality comparison may
not return true.
Terms related to arithmetic expressions
Murach's JavaScript and jQuery (3rd Ed.)
© 2017, Mike Murach & Associates, Inc. C2, Slide 35
 arithmetic expression
 arithmetic operators
 order of precedence
 compound assignment operators
The concatenation operators for strings
Murach's JavaScript and jQuery (3rd Ed.)
© 2017, Mike Murach & Associates, Inc. C2, Slide 36
Operator Description
+ Concatenates two values.
+= Adds the result of the expression
to the end of the variable.
How to concatenate string variables
with the + operator
var firstName = "Grace", lastName = "Hopper";
var fullName = lastName + ", " + firstName;
// fullName is "Hopper, Grace"
How to concatenate string variables
with the += operator
var firstName = "Grace", lastName = "Hopper";
var fullName = lastName; // fullName is "Hopper"
fullName += ", "; // fullName is "Hopper, "
fullName += firstName; // fullName is "Hopper, Grace"
How to concatenate a string and a number
with the + operator
Murach's JavaScript and jQuery (3rd Ed.)
© 2017, Mike Murach & Associates, Inc. C2, Slide 37
var months = 120;
var message = "Months: ";
message = message + months; // message is "Months: 120"
How to concatenate a string and a number
with the += operator
var months = 120;
var message = "Months: ";
message += months; // message is "Months: 120"
Some of the escape sequences that can be used
in strings
Murach's JavaScript and jQuery (3rd Ed.)
© 2017, Mike Murach & Associates, Inc. C2, Slide 38
Operator Description
n Starts a new line in a string.
" Puts a double quotation mark in a string.
' Puts a single quotation mark in a string.
How escape sequences can be used in a string
var message = "A valid variable namencannot start with a number.";
var message = "This isn't the right way to do this.";
Terms related to strings
Murach's JavaScript and jQuery (3rd Ed.)
© 2017, Mike Murach & Associates, Inc. C2, Slide 39
 concatenate (join) strings
 concatenation operators
 string expression
 escape sequences
Common methods of the window object
Murach's JavaScript and jQuery (3rd Ed.)
© 2017, Mike Murach & Associates, Inc. C2, Slide 40
alert(string)
prompt(string, default)
print()
The syntax for calling a method of an object
objectName.methodName(parameters)
A statement that calls the alert() method
of the window object
window.alert("This is a test of the alert method");
A statement that calls the prompt() method
with the object name omitted
Murach's JavaScript and jQuery (3rd Ed.)
© 2017, Mike Murach & Associates, Inc. C2, Slide 41
var userEntry =
prompt("This is a test of the prompt method", 100);
The prompt dialog box that’s displayed
One property of the window object
Murach's JavaScript and jQuery (3rd Ed.)
© 2017, Mike Murach & Associates, Inc. C2, Slide 42
location
The syntax for accessing a property of an object
objectName.propertyName
A statement that displays
the URL of the current page
alert(window.location);
Two methods of the window object
Murach's JavaScript and jQuery (3rd Ed.)
© 2017, Mike Murach & Associates, Inc. C2, Slide 43
parseInt(string)
parseFloat(string)
The parsing that’s done by the parse methods
 Only the first number in the string is returned.
 Leading and trailing spaces are removed.
 If the first character cannot be converted to a number, NaN is
returned.
Examples that use the parseInt()
and parseFloat() methods
Murach's JavaScript and jQuery (3rd Ed.)
© 2017, Mike Murach & Associates, Inc. C2, Slide 44
var entryA = prompt("Enter any value", 12345.6789);
alert(entryA); // displays 12345.6789
entryA = parseInt(entryA);
alert(entryA); // displays 12345
var entryB = prompt("Enter any value", 12345.6789);
alert(entryB); // displays 12345.6789
entryB = parseFloat(entryB);
alert(entryB); // displays 12345.6789
var entryC = prompt("Enter any value", "Hello");
alert(entryC); // displays Hello
entryC = parseInt(entryC);
alert(entryC); // displays NaN
The same examples with the parse methods
embedded in the alert() method
Murach's JavaScript and jQuery (3rd Ed.)
© 2017, Mike Murach & Associates, Inc. C2, Slide 45
var entryA = prompt("Enter any value", 12345.6789);
alert(entryA); // displays 12345.6789
alert(parseInt(entryA)); // displays 12345
var entryB = prompt("Enter any value", 12345.6789);
alert(entryB); // displays 12345.6789
alert(parseFloat(entryB)); // displays 12345.6789
var entryC = prompt("Enter any value", "Hello");
alert(entryC); // displays Hello
alert(parseInt(entryC)); // displays NaN
Two methods of the document object
Murach's JavaScript and jQuery (3rd Ed.)
© 2017, Mike Murach & Associates, Inc. C2, Slide 46
write(string)
writeln(string)
Examples of the write() and writeln() methods
Murach's JavaScript and jQuery (3rd Ed.)
© 2017, Mike Murach & Associates, Inc. C2, Slide 47
<body>
<script>
var today = new Date();
document.write("<h1>Welcome to our site!</h1>");
document.write("Today is ");
document.write(today.toDateString());
document.write("<br>");
document.writeln("Today is ");
document.writeln(today.toDateString());
document.write("<br>");
</script>
<script>
document.writeln("Welcome to our site!");
document.writeln("Today is Monday.");
</script>
<script>
document.writeln("<pre>Welcome to our site!");
document.writeln("Today is Monday.</pre>");
</script>
</body>
The output in a browser
Murach's JavaScript and jQuery (3rd Ed.)
© 2017, Mike Murach & Associates, Inc. C2, Slide 48
Terms related to objects
Murach's JavaScript and jQuery (3rd Ed.)
© 2017, Mike Murach & Associates, Inc. C2, Slide 49
 object
 method
 property
 call a method
 parameter
 window object
 global object
 dot operator
 document object
The Calculate MPG application
Murach's JavaScript and jQuery (3rd Ed.)
© 2017, Mike Murach & Associates, Inc. C2, Slide 50
The first prompt dialog box
The second prompt dialog box
The Calculate MPG application (continued)
Murach's JavaScript and jQuery (3rd Ed.)
© 2017, Mike Murach & Associates, Inc. C2, Slide 51
The alert dialog box that displays the result
The HTML and JavaScript for the application
Murach's JavaScript and jQuery (3rd Ed.)
© 2017, Mike Murach & Associates, Inc. C2, Slide 52
<html>
<head>
<title>The Calculate MPG Application</title>
<script>
var miles = prompt("Enter miles driven");
miles = parseFloat(miles);
var gallons = prompt("Enter gallons of gas used");
gallons = parseFloat(gallons);
var mpg = miles/gallons;
mpg = parseInt(mpg);
alert("Miles per gallon = " + mpg);
</script>
</head>
<body>
<!-- Will show after the JavaScript has run -->
<h1>Thanks for using the Miles Per Gallon
application!</h1>
</body>
</html>
The results of the Test Scores application
in a browser
Murach's JavaScript and jQuery (3rd Ed.)
© 2017, Mike Murach & Associates, Inc. C2, Slide 53
The HTML and JavaScript for the application
Murach's JavaScript and jQuery (3rd Ed.)
© 2017, Mike Murach & Associates, Inc. C2, Slide 54
<html>
<head>
<title>Average Test Scores</title>
<script>
var entry;
var average;
var total = 0;
//get 3 scores from user and add them together
entry = prompt("Enter test score");
entry = parseInt(entry);
var score1 = entry;
total = total + score1;
entry = prompt("Enter test score");
entry = parseInt(entry);
var score2 = entry;
total = total + score2;
The HTML and JavaScript (cont.)
Murach's JavaScript and jQuery (3rd Ed.)
© 2017, Mike Murach & Associates, Inc. C2, Slide 55
entry = prompt("Enter test score");
entry = parseInt(entry);
var score3 = entry;
total = total + score3;
//calculate the average
average = parseInt(total/3);
</script>
</head>
<body>
<script>
document.write("<h1>The Test Scores App</h1>");
document.write("Score 1 = " + score1 + "<br>" +
"Score 2 = " + score2 + "<br>" +
"Score 3 = " + score3 + "<br><br>" +
"Average score = " + average + "<br><br>");
</script>
Thanks for using the Test Scores application!
</body>
</html>
Exercise 2-1 Modify the MPG application
Murach's JavaScript and jQuery (3rd Ed.)
© 2017, Mike Murach & Associates, Inc. C2, Slide 56
Display the output in the browser, not in an alert dialog
box.
Exercise 2-3 Create a simple application
Murach's JavaScript and jQuery (3rd Ed.)
© 2017, Mike Murach & Associates, Inc. C2, Slide 57
Start with the MPG app and change it into a new app.
Extra 2-1 Convert Fahrenheit to Celsius
Murach's JavaScript and jQuery (3rd Ed.)
© 2017, Mike Murach & Associates, Inc. C2, Slide 58
The prompt dialog box
The alert dialog box
To convert F to C subtract 32 from F and multiply by 5/9.
Short 2-1 Modify the Test Scores application
Murach's JavaScript and jQuery (3rd Ed.)
© 2017, Mike Murach & Associates, Inc. C2, Slide 59
Estimated time: 10 to 20 minutes.
Provide for a fourth score and display the results in a
dialog box.

More Related Content

Similar to Javascript_JQUERY_Desiging_Modules_User_interface_working_managing_html_codes.pptx

Advanced+qtp+open+order
Advanced+qtp+open+orderAdvanced+qtp+open+order
Advanced+qtp+open+orderRamu Palanki
 
Javascript tutorial basic for starter
Javascript tutorial basic for starterJavascript tutorial basic for starter
Javascript tutorial basic for starterMarcello Harford
 
Ch3- Java Script.pdf
Ch3- Java Script.pdfCh3- Java Script.pdf
Ch3- Java Script.pdfHASENSEID
 
C# Tutorial MSM_Murach chapter-12-slides
C# Tutorial MSM_Murach chapter-12-slidesC# Tutorial MSM_Murach chapter-12-slides
C# Tutorial MSM_Murach chapter-12-slidesSami Mut
 
21 ijaprr vol1-3-12-17juni
21 ijaprr vol1-3-12-17juni21 ijaprr vol1-3-12-17juni
21 ijaprr vol1-3-12-17juniijaprr_editor
 
Ch-3(b) - Variables and Data types in C++.pptx
Ch-3(b) - Variables and Data types in C++.pptxCh-3(b) - Variables and Data types in C++.pptx
Ch-3(b) - Variables and Data types in C++.pptxChereLemma2
 
Murach: How to validate data in asp.net core mvc
Murach: How to validate data in asp.net core mvcMurach: How to validate data in asp.net core mvc
Murach: How to validate data in asp.net core mvcMahmoudOHassouna
 
Actionscript Standards
Actionscript StandardsActionscript Standards
Actionscript StandardsKapil Mohan
 
Basics of Javascript
Basics of Javascript Basics of Javascript
Basics of Javascript poojanov04
 
Introduction to javascript.ppt
Introduction to javascript.pptIntroduction to javascript.ppt
Introduction to javascript.pptBArulmozhi
 
Advanced Qtp Book
Advanced Qtp BookAdvanced Qtp Book
Advanced Qtp BookG.C Reddy
 
Computer fundamentals
Computer fundamentalsComputer fundamentals
Computer fundamentalssameer sheikh
 
22316-2019-Summer-model-answer-paper.pdf
22316-2019-Summer-model-answer-paper.pdf22316-2019-Summer-model-answer-paper.pdf
22316-2019-Summer-model-answer-paper.pdfPradipShinde53
 
8.-Javascript-report powerpoint presentation
8.-Javascript-report powerpoint presentation8.-Javascript-report powerpoint presentation
8.-Javascript-report powerpoint presentationJohnLagman3
 
Estudios Sociales Y Civica Media 0
Estudios Sociales Y Civica Media 0Estudios Sociales Y Civica Media 0
Estudios Sociales Y Civica Media 0guest4dfcdf6
 

Similar to Javascript_JQUERY_Desiging_Modules_User_interface_working_managing_html_codes.pptx (20)

Web programming
Web programmingWeb programming
Web programming
 
Advanced+qtp+open+order
Advanced+qtp+open+orderAdvanced+qtp+open+order
Advanced+qtp+open+order
 
Javascript tutorial basic for starter
Javascript tutorial basic for starterJavascript tutorial basic for starter
Javascript tutorial basic for starter
 
JavaScript
JavaScriptJavaScript
JavaScript
 
3. Java Script
3. Java Script3. Java Script
3. Java Script
 
Ch3- Java Script.pdf
Ch3- Java Script.pdfCh3- Java Script.pdf
Ch3- Java Script.pdf
 
Java script
Java scriptJava script
Java script
 
Vbs
VbsVbs
Vbs
 
C# Tutorial MSM_Murach chapter-12-slides
C# Tutorial MSM_Murach chapter-12-slidesC# Tutorial MSM_Murach chapter-12-slides
C# Tutorial MSM_Murach chapter-12-slides
 
21 ijaprr vol1-3-12-17juni
21 ijaprr vol1-3-12-17juni21 ijaprr vol1-3-12-17juni
21 ijaprr vol1-3-12-17juni
 
Ch-3(b) - Variables and Data types in C++.pptx
Ch-3(b) - Variables and Data types in C++.pptxCh-3(b) - Variables and Data types in C++.pptx
Ch-3(b) - Variables and Data types in C++.pptx
 
Murach: How to validate data in asp.net core mvc
Murach: How to validate data in asp.net core mvcMurach: How to validate data in asp.net core mvc
Murach: How to validate data in asp.net core mvc
 
Actionscript Standards
Actionscript StandardsActionscript Standards
Actionscript Standards
 
Basics of Javascript
Basics of Javascript Basics of Javascript
Basics of Javascript
 
Introduction to javascript.ppt
Introduction to javascript.pptIntroduction to javascript.ppt
Introduction to javascript.ppt
 
Advanced Qtp Book
Advanced Qtp BookAdvanced Qtp Book
Advanced Qtp Book
 
Computer fundamentals
Computer fundamentalsComputer fundamentals
Computer fundamentals
 
22316-2019-Summer-model-answer-paper.pdf
22316-2019-Summer-model-answer-paper.pdf22316-2019-Summer-model-answer-paper.pdf
22316-2019-Summer-model-answer-paper.pdf
 
8.-Javascript-report powerpoint presentation
8.-Javascript-report powerpoint presentation8.-Javascript-report powerpoint presentation
8.-Javascript-report powerpoint presentation
 
Estudios Sociales Y Civica Media 0
Estudios Sociales Y Civica Media 0Estudios Sociales Y Civica Media 0
Estudios Sociales Y Civica Media 0
 

Recently uploaded

Using IESVE for Room Loads Analysis - UK & Ireland
Using IESVE for Room Loads Analysis - UK & IrelandUsing IESVE for Room Loads Analysis - UK & Ireland
Using IESVE for Room Loads Analysis - UK & IrelandIES VE
 
State of the Smart Building Startup Landscape 2024!
State of the Smart Building Startup Landscape 2024!State of the Smart Building Startup Landscape 2024!
State of the Smart Building Startup Landscape 2024!Memoori
 
The Zero-ETL Approach: Enhancing Data Agility and Insight
The Zero-ETL Approach: Enhancing Data Agility and InsightThe Zero-ETL Approach: Enhancing Data Agility and Insight
The Zero-ETL Approach: Enhancing Data Agility and InsightSafe Software
 
Top 10 CodeIgniter Development Companies
Top 10 CodeIgniter Development CompaniesTop 10 CodeIgniter Development Companies
Top 10 CodeIgniter Development CompaniesTopCSSGallery
 
(Explainable) Data-Centric AI: what are you explaininhg, and to whom?
(Explainable) Data-Centric AI: what are you explaininhg, and to whom?(Explainable) Data-Centric AI: what are you explaininhg, and to whom?
(Explainable) Data-Centric AI: what are you explaininhg, and to whom?Paolo Missier
 
Introduction to FIDO Authentication and Passkeys.pptx
Introduction to FIDO Authentication and Passkeys.pptxIntroduction to FIDO Authentication and Passkeys.pptx
Introduction to FIDO Authentication and Passkeys.pptxFIDO Alliance
 
Hyatt driving innovation and exceptional customer experiences with FIDO passw...
Hyatt driving innovation and exceptional customer experiences with FIDO passw...Hyatt driving innovation and exceptional customer experiences with FIDO passw...
Hyatt driving innovation and exceptional customer experiences with FIDO passw...FIDO Alliance
 
Continuing Bonds Through AI: A Hermeneutic Reflection on Thanabots
Continuing Bonds Through AI: A Hermeneutic Reflection on ThanabotsContinuing Bonds Through AI: A Hermeneutic Reflection on Thanabots
Continuing Bonds Through AI: A Hermeneutic Reflection on ThanabotsLeah Henrickson
 
WebRTC and SIP not just audio and video @ OpenSIPS 2024
WebRTC and SIP not just audio and video @ OpenSIPS 2024WebRTC and SIP not just audio and video @ OpenSIPS 2024
WebRTC and SIP not just audio and video @ OpenSIPS 2024Lorenzo Miniero
 
1111 ChatGPT Prompts PDF Free Download - Prompts for ChatGPT
1111 ChatGPT Prompts PDF Free Download - Prompts for ChatGPT1111 ChatGPT Prompts PDF Free Download - Prompts for ChatGPT
1111 ChatGPT Prompts PDF Free Download - Prompts for ChatGPTiSEO AI
 
WebAssembly is Key to Better LLM Performance
WebAssembly is Key to Better LLM PerformanceWebAssembly is Key to Better LLM Performance
WebAssembly is Key to Better LLM PerformanceSamy Fodil
 
Harnessing Passkeys in the Battle Against AI-Powered Cyber Threats.pptx
Harnessing Passkeys in the Battle Against AI-Powered Cyber Threats.pptxHarnessing Passkeys in the Battle Against AI-Powered Cyber Threats.pptx
Harnessing Passkeys in the Battle Against AI-Powered Cyber Threats.pptxFIDO Alliance
 
Event-Driven Architecture Masterclass: Challenges in Stream Processing
Event-Driven Architecture Masterclass: Challenges in Stream ProcessingEvent-Driven Architecture Masterclass: Challenges in Stream Processing
Event-Driven Architecture Masterclass: Challenges in Stream ProcessingScyllaDB
 
TrustArc Webinar - Unified Trust Center for Privacy, Security, Compliance, an...
TrustArc Webinar - Unified Trust Center for Privacy, Security, Compliance, an...TrustArc Webinar - Unified Trust Center for Privacy, Security, Compliance, an...
TrustArc Webinar - Unified Trust Center for Privacy, Security, Compliance, an...TrustArc
 
Easier, Faster, and More Powerful – Alles Neu macht der Mai -Wir durchleuchte...
Easier, Faster, and More Powerful – Alles Neu macht der Mai -Wir durchleuchte...Easier, Faster, and More Powerful – Alles Neu macht der Mai -Wir durchleuchte...
Easier, Faster, and More Powerful – Alles Neu macht der Mai -Wir durchleuchte...panagenda
 
Design Guidelines for Passkeys 2024.pptx
Design Guidelines for Passkeys 2024.pptxDesign Guidelines for Passkeys 2024.pptx
Design Guidelines for Passkeys 2024.pptxFIDO Alliance
 
Revolutionizing SAP® Processes with Automation and Artificial Intelligence
Revolutionizing SAP® Processes with Automation and Artificial IntelligenceRevolutionizing SAP® Processes with Automation and Artificial Intelligence
Revolutionizing SAP® Processes with Automation and Artificial IntelligencePrecisely
 
The Metaverse: Are We There Yet?
The  Metaverse:    Are   We  There  Yet?The  Metaverse:    Are   We  There  Yet?
The Metaverse: Are We There Yet?Mark Billinghurst
 
Intro to Passkeys and the State of Passwordless.pptx
Intro to Passkeys and the State of Passwordless.pptxIntro to Passkeys and the State of Passwordless.pptx
Intro to Passkeys and the State of Passwordless.pptxFIDO Alliance
 
Event-Driven Architecture Masterclass: Engineering a Robust, High-performance...
Event-Driven Architecture Masterclass: Engineering a Robust, High-performance...Event-Driven Architecture Masterclass: Engineering a Robust, High-performance...
Event-Driven Architecture Masterclass: Engineering a Robust, High-performance...ScyllaDB
 

Recently uploaded (20)

Using IESVE for Room Loads Analysis - UK & Ireland
Using IESVE for Room Loads Analysis - UK & IrelandUsing IESVE for Room Loads Analysis - UK & Ireland
Using IESVE for Room Loads Analysis - UK & Ireland
 
State of the Smart Building Startup Landscape 2024!
State of the Smart Building Startup Landscape 2024!State of the Smart Building Startup Landscape 2024!
State of the Smart Building Startup Landscape 2024!
 
The Zero-ETL Approach: Enhancing Data Agility and Insight
The Zero-ETL Approach: Enhancing Data Agility and InsightThe Zero-ETL Approach: Enhancing Data Agility and Insight
The Zero-ETL Approach: Enhancing Data Agility and Insight
 
Top 10 CodeIgniter Development Companies
Top 10 CodeIgniter Development CompaniesTop 10 CodeIgniter Development Companies
Top 10 CodeIgniter Development Companies
 
(Explainable) Data-Centric AI: what are you explaininhg, and to whom?
(Explainable) Data-Centric AI: what are you explaininhg, and to whom?(Explainable) Data-Centric AI: what are you explaininhg, and to whom?
(Explainable) Data-Centric AI: what are you explaininhg, and to whom?
 
Introduction to FIDO Authentication and Passkeys.pptx
Introduction to FIDO Authentication and Passkeys.pptxIntroduction to FIDO Authentication and Passkeys.pptx
Introduction to FIDO Authentication and Passkeys.pptx
 
Hyatt driving innovation and exceptional customer experiences with FIDO passw...
Hyatt driving innovation and exceptional customer experiences with FIDO passw...Hyatt driving innovation and exceptional customer experiences with FIDO passw...
Hyatt driving innovation and exceptional customer experiences with FIDO passw...
 
Continuing Bonds Through AI: A Hermeneutic Reflection on Thanabots
Continuing Bonds Through AI: A Hermeneutic Reflection on ThanabotsContinuing Bonds Through AI: A Hermeneutic Reflection on Thanabots
Continuing Bonds Through AI: A Hermeneutic Reflection on Thanabots
 
WebRTC and SIP not just audio and video @ OpenSIPS 2024
WebRTC and SIP not just audio and video @ OpenSIPS 2024WebRTC and SIP not just audio and video @ OpenSIPS 2024
WebRTC and SIP not just audio and video @ OpenSIPS 2024
 
1111 ChatGPT Prompts PDF Free Download - Prompts for ChatGPT
1111 ChatGPT Prompts PDF Free Download - Prompts for ChatGPT1111 ChatGPT Prompts PDF Free Download - Prompts for ChatGPT
1111 ChatGPT Prompts PDF Free Download - Prompts for ChatGPT
 
WebAssembly is Key to Better LLM Performance
WebAssembly is Key to Better LLM PerformanceWebAssembly is Key to Better LLM Performance
WebAssembly is Key to Better LLM Performance
 
Harnessing Passkeys in the Battle Against AI-Powered Cyber Threats.pptx
Harnessing Passkeys in the Battle Against AI-Powered Cyber Threats.pptxHarnessing Passkeys in the Battle Against AI-Powered Cyber Threats.pptx
Harnessing Passkeys in the Battle Against AI-Powered Cyber Threats.pptx
 
Event-Driven Architecture Masterclass: Challenges in Stream Processing
Event-Driven Architecture Masterclass: Challenges in Stream ProcessingEvent-Driven Architecture Masterclass: Challenges in Stream Processing
Event-Driven Architecture Masterclass: Challenges in Stream Processing
 
TrustArc Webinar - Unified Trust Center for Privacy, Security, Compliance, an...
TrustArc Webinar - Unified Trust Center for Privacy, Security, Compliance, an...TrustArc Webinar - Unified Trust Center for Privacy, Security, Compliance, an...
TrustArc Webinar - Unified Trust Center for Privacy, Security, Compliance, an...
 
Easier, Faster, and More Powerful – Alles Neu macht der Mai -Wir durchleuchte...
Easier, Faster, and More Powerful – Alles Neu macht der Mai -Wir durchleuchte...Easier, Faster, and More Powerful – Alles Neu macht der Mai -Wir durchleuchte...
Easier, Faster, and More Powerful – Alles Neu macht der Mai -Wir durchleuchte...
 
Design Guidelines for Passkeys 2024.pptx
Design Guidelines for Passkeys 2024.pptxDesign Guidelines for Passkeys 2024.pptx
Design Guidelines for Passkeys 2024.pptx
 
Revolutionizing SAP® Processes with Automation and Artificial Intelligence
Revolutionizing SAP® Processes with Automation and Artificial IntelligenceRevolutionizing SAP® Processes with Automation and Artificial Intelligence
Revolutionizing SAP® Processes with Automation and Artificial Intelligence
 
The Metaverse: Are We There Yet?
The  Metaverse:    Are   We  There  Yet?The  Metaverse:    Are   We  There  Yet?
The Metaverse: Are We There Yet?
 
Intro to Passkeys and the State of Passwordless.pptx
Intro to Passkeys and the State of Passwordless.pptxIntro to Passkeys and the State of Passwordless.pptx
Intro to Passkeys and the State of Passwordless.pptx
 
Event-Driven Architecture Masterclass: Engineering a Robust, High-performance...
Event-Driven Architecture Masterclass: Engineering a Robust, High-performance...Event-Driven Architecture Masterclass: Engineering a Robust, High-performance...
Event-Driven Architecture Masterclass: Engineering a Robust, High-performance...
 

Javascript_JQUERY_Desiging_Modules_User_interface_working_managing_html_codes.pptx

  • 1. Chapter 2 Murach's JavaScript and jQuery (3rd Ed.) © 2017, Mike Murach & Associates, Inc. Getting started with JavaScript C2, Slide 1
  • 2. Objectives Murach's JavaScript and jQuery (3rd Ed.) © 2017, Mike Murach & Associates, Inc. Applied 1. Given the specifications for a JavaScript application that requires only the skills that you’ve learned so far, code, test, and debug the application. Knowledge 1. Describe two ways to include JavaScript in the head of an HTML document. 2. Describe how JavaScript can be included in the body of an HTML document. 3. Describe how case-sensitivity, semicolons, and whitespace relate to the syntax for a JavaScript statement. 4. List the primary rules for creating a JavaScript identifier. 5. Describe the use of JavaScript comments, including “commenting out” portions of JavaScript code. C2, Slide 2
  • 3. Objectives (continued) Murach's JavaScript and jQuery (3rd Ed.) © 2017, Mike Murach & Associates, Inc. 6. Describe the three primitive data types used in JavaScript: numeric, string, and Boolean. 7. Describe the use of variable declarations and assignment statements with numeric, string, and Boolean data. 8. Describe the use of the arithmetic operators and the rules for evaluating an arithmetic expression, including order of precedence and the use of parentheses. 9. Describe the use of the + operator and the n escape sequence when working with strings. 10.Describe the syntax for referring to a method or property of an object. 11.Describe the use of the alert(), prompt(), parseInt(), parseFloat(), write(), and writeln() methods. C2, Slide 3
  • 4. Two attributes of the script element Murach's JavaScript and jQuery (3rd Ed.) © 2017, Mike Murach & Associates, Inc. C2, Slide 4 src type A script element in the head section that loads an external JavaScript file <script src="calculate_mpg.js"></script>
  • 5. A script element that embeds JavaScript in the head section Murach's JavaScript and jQuery (3rd Ed.) © 2017, Mike Murach & Associates, Inc. C2, Slide 5 <head> ... <script> alert("The Calculate MPG application"); var miles = prompt("Enter miles driven"); miles = parseFloat(miles); var gallons = prompt("Enter gallons of gas used"); gallons = parseFloat(gallons); var mpg = miles/gallons; mpg = parseInt(mpg); alert("Miles per gallon = " + mpg); </script> </head>
  • 6. Terms Murach's JavaScript and jQuery (3rd Ed.) © 2017, Mike Murach & Associates, Inc.  external JavaScript file  embedded JavaScript C2, Slide 6
  • 7. JavaScript in the body of an HTML document Murach's JavaScript and jQuery (3rd Ed.) © 2017, Mike Murach & Associates, Inc. C2, Slide 7 <p> <script> var today = new Date(); document.write("Current date: "); document.write(today.toDateString()); </script> </p> <p>&copy;&nbsp; <script> var today = new Date(); document.write( today.getFullYear() ); </script> , San Joaquin Valley Town Hall </p>
  • 8. The result of the JavaScript in a web browser Murach's JavaScript and jQuery (3rd Ed.) © 2017, Mike Murach & Associates, Inc. C2, Slide 8
  • 9. A noscript element in the body of an HTML document Murach's JavaScript and jQuery (3rd Ed.) © 2017, Mike Murach & Associates, Inc. C2, Slide 9 <p>&copy;&nbsp; <script> var today = new Date(); document.write( today.getFullYear() ); </script> <noscript>2017</noscript> , San Joaquin Valley Town Hall </p>
  • 10. A noscript element at the start of an HTML document Murach's JavaScript and jQuery (3rd Ed.) © 2017, Mike Murach & Associates, Inc. C2, Slide 10 <h2> <noscript> To get the most from this website, please enable JavaScript. </noscript> </h2>
  • 11. A block of JavaScript code Murach's JavaScript and jQuery (3rd Ed.) © 2017, Mike Murach & Associates, Inc. C2, Slide 11 var joinList = function () { var emailAddress1 = $("email_address1").value; var emailAddress2 = $("email_address2").value; if (emailAddress1 == "") { alert("Email Address is required."); } else if (emailAddress2 == "") { alert("Second Email Address is required."); } else if (emailAddress1 !== emailAddress2) { alert("Second Email entry must equal first entry."); } else if ($("first_name").value == "") { alert("First Name is required."); } else { $("email_form").submit(); } }
  • 12. The basic syntax rules for JavaScript Murach's JavaScript and jQuery (3rd Ed.) © 2017, Mike Murach & Associates, Inc.  JavaScript is case-sensitive.  Each JavaScript statement ends with a semicolon.  JavaScript ignores extra whitespace within statements. C2, Slide 12
  • 13. How to split a statement over two or more lines Murach's JavaScript and jQuery (3rd Ed.) © 2017, Mike Murach & Associates, Inc. C2, Slide 13  Split a statement after: an arithmetic or relational operator like +, -, *, /, =, ==, >, or < an opening brace ( { ), bracket ( [ ), or parenthesis a closing brace ( } )  Do not split a statement after: an identifier, a value, or the return keyword a closing bracket ( ] ) or parenthesis
  • 14. Rules for creating identifiers Murach's JavaScript and jQuery (3rd Ed.) © 2017, Mike Murach & Associates, Inc. C2, Slide 14  Identifiers can only contain letters, numbers, the underscore, and the dollar sign.  Identifiers can’t start with a number.  Identifiers are case-sensitive.  Identifiers can be any length.  Identifiers can’t be the same as reserved words.  Avoid using global properties and methods as identifiers.
  • 15. Valid identifiers in JavaScript Murach's JavaScript and jQuery (3rd Ed.) © 2017, Mike Murach & Associates, Inc. subtotal index_1 $ taxRate calculate_click $log C2, Slide 15
  • 16. Camel casing versus underscore notation Murach's JavaScript and jQuery (3rd Ed.) © 2017, Mike Murach & Associates, Inc. C2, Slide 16 taxRate tax_rate calculateClick calculate_click emailAddress email_address futureValue future_value
  • 17. Naming recommendations for identifiers Murach's JavaScript and jQuery (3rd Ed.) © 2017, Mike Murach & Associates, Inc. C2, Slide 17  Use meaningful names. That way, your identifiers aren’t likely to be reserved words or global properties.  Be consistent: Either use camel casing (taxRate) or underscores (tax_rate) to identify the words within the variables in your scripts.  If you’re using underscore notation, use lowercase for all letters.
  • 18. JavaScript code with the comments highlighted Murach's JavaScript and jQuery (3rd Ed.) © 2017, Mike Murach & Associates, Inc. C2, Slide 18 /* this application validates a user's entries for joining our email list */ var $ = function(id) { // the $ function return document.getElementById(id); } // this function gets and validates the user entries var joinList = function() { var emailAddress1 = $("email_address1").value; var emailAddress2 = $("email_address2").value; var firstName = $("first_name").value; var isValid = true; // validate the first entry if (emailAddress1 == "") { $("email_address1_error").firstChild.nodeValue = "This field is required."; isValid = false; // set valid switch to off } else { $("email_address1_error").firstChild.nodeValue = ""; } // validate the second entry ... ... };
  • 19. The basic syntax rules for comments Murach's JavaScript and jQuery (3rd Ed.) © 2017, Mike Murach & Associates, Inc. C2, Slide 19  Block comments begin with /* and end with */.  Single-line comments begin with two forward slashes and continue to the end of the line. Guidelines for using comments  Use comments to describe portions of code that are hard to understand.  Use comments to disable portions of code that you don’t want to test.  Don’t use comments unnecessarily.
  • 20. Terms Murach's JavaScript and jQuery (3rd Ed.) © 2017, Mike Murach & Associates, Inc.  statement  whitespace  identifier  camel casing  comment  comment out C2, Slide 20
  • 21. JavaScript’s primitive data types Murach's JavaScript and jQuery (3rd Ed.) © 2017, Mike Murach & Associates, Inc. C2, Slide 21  Number  String  Boolean
  • 22. Examples of number values Murach's JavaScript and jQuery (3rd Ed.) © 2017, Mike Murach & Associates, Inc. C2, Slide 22 15 // an integer -21 // a negative integer 21.5 // a decimal value -124.82 // a negative decimal value -3.7e-9 // floating-point notation for -0.0000000037 The number data type  A number value can be an integer or a decimal value.  In JavaScript, decimal values are stored as floating-point numbers.  If a result is stored in a number data type that is larger or smaller than the data type can store, it will be stored as the value Infinity or -Infinity.
  • 23. Examples of string values Murach's JavaScript and jQuery (3rd Ed.) © 2017, Mike Murach & Associates, Inc. C2, Slide 23 "JavaScript" // a string with double quotes 'String Data' // a string with single quotes "" // an empty string The string data type  A string value is surrounded by double quotes or single quotes. The string must start and end with the same type of quotation mark.  An empty string is a string that contains no characters. It is entered by typing two quotation marks with nothing between them.
  • 24. The two Boolean values Murach's JavaScript and jQuery (3rd Ed.) © 2017, Mike Murach & Associates, Inc. C2, Slide 24 true // equivalent to true, yes, or on false // equivalent to false, no, or off The Boolean data type  A Boolean value can be true or false. Boolean values are often used in conditional statements.
  • 25. How to declare and assign a value to a variable in two statements Murach's JavaScript and jQuery (3rd Ed.) © 2017, Mike Murach & Associates, Inc. C2, Slide 25 Syntax var variableName; variableName = value; Examples var counter; // declaration statement; // value is undefined counter = 1; // assignment statement; // value is 1 var sum, average; // declares two variables sum = 0, average = 0; // assigns values to two // variables
  • 26. How to declare and assign a value to a variable in one statement Murach's JavaScript and jQuery (3rd Ed.) © 2017, Mike Murach & Associates, Inc. C2, Slide 26 Syntax var variableName = value; Examples var count = 1; // integer value of 1 var subtotal = 74.95; // decimal value of 74.95 var name = "Joseph"; // string value of "Joseph" var email = ""; // empty string var isValid = false; // Boolean value of false var total = subtotal; // assigns value of subtotal variable var x = 0, y = 0; // declares and assigns values to 2 variables
  • 27. Terms Murach's JavaScript and jQuery (3rd Ed.) © 2017, Mike Murach & Associates, Inc. C2, Slide 27  variable  declare a variable  assignment statement  assignment operator  literal value  literal  string literal  numeric literal
  • 28. JavaScript’s arithmetic operators Murach's JavaScript and jQuery (3rd Ed.) © 2017, Mike Murach & Associates, Inc. C2, Slide 28 Operator Name Description + Addition Adds two operands. - Subtraction Subtracts the right operand from the left operand. * Multiplication Multiplies two operands. / Division Divides the right operand into the left operand. The result is always a floating-point number. % Modulus Divides the right operand into the left operand and returns the remainder. ++ Increment Adds 1 to the operand. -- Decrement Subtracts 1 from the operand.
  • 29. The order of precedence for arithmetic expressions Murach's JavaScript and jQuery (3rd Ed.) © 2017, Mike Murach & Associates, Inc. C2, Slide 29 Order Operators Direction Description 1 ++ Left to right Increment operator 2 -- Left to right Decrement operator 3 * / % Left to right Multiplication, division, modulus 4 + - Left to right Addition, subtraction
  • 30. Examples of simple arithmetic expressions Murach's JavaScript and jQuery (3rd Ed.) © 2017, Mike Murach & Associates, Inc. C2, Slide 30 Example Result 5 + 7 12 5 - 12 -7 6 * 7 42 13 / 4 3.25 13 % 4 1 counter++ counter = counter + 1 counter-- counter = counter – 1 3 + 4 * 5 23 (the multiplication is done first) (3 + 4) * 5 35 (the addition is done first) 13 % 4 + 9 10 (the modulus is done first) 13 % (4 + 9) 0 (the addition is done first)
  • 31. Code that calculates sales tax Murach's JavaScript and jQuery (3rd Ed.) © 2017, Mike Murach & Associates, Inc. C2, Slide 31 var subtotal = 200; var taxPercent = .05; var taxAmount = subtotal * taxPercent; // 10 var total = subtotal + taxAmount; // 210 Code that calculates the perimeter of a rectangle var width = 4.25; var length = 8.5; var perimeter = (2 * width) + (2 * length) // (8.5 + 17) = 25.5
  • 32. The most useful compound assignment operators Murach's JavaScript and jQuery (3rd Ed.) © 2017, Mike Murach & Associates, Inc. C2, Slide 32 Operator Description += Adds the result of the expression to the variable. -= Subtracts the result of the expression from the variable. *= Multiplies the variable value by the result of the expression. Statements with compound assignment operators var subtotal = 74.95; subtotal += 20.00; // subtotal = 94.95 var counter = 10; counter -= 1; // counter = 9 var price = 100; price *= .8; // price = 80
  • 33. Three ways to increment a counter variable by 1 Murach's JavaScript and jQuery (3rd Ed.) © 2017, Mike Murach & Associates, Inc. C2, Slide 33 var counter = 1; // counter = 1 counter = counter + 1; // counter now = 2 counter += 1; // counter now = 3 counter++; // counter now = 4
  • 34. A floating-point result that isn’t precise Murach's JavaScript and jQuery (3rd Ed.) © 2017, Mike Murach & Associates, Inc. C2, Slide 34 var subtotal = 74.95; // subtotal = 74.95 var salesTax = subtotal * .1; // salesTax = 7.495000000000001 A problem with some arithmetic operations  When you do some types of arithmetic operations with decimal values, the results aren’t always precise. That’s because decimal values are stored internally as floating-point numbers.  The primary problem with this is that an equality comparison may not return true.
  • 35. Terms related to arithmetic expressions Murach's JavaScript and jQuery (3rd Ed.) © 2017, Mike Murach & Associates, Inc. C2, Slide 35  arithmetic expression  arithmetic operators  order of precedence  compound assignment operators
  • 36. The concatenation operators for strings Murach's JavaScript and jQuery (3rd Ed.) © 2017, Mike Murach & Associates, Inc. C2, Slide 36 Operator Description + Concatenates two values. += Adds the result of the expression to the end of the variable. How to concatenate string variables with the + operator var firstName = "Grace", lastName = "Hopper"; var fullName = lastName + ", " + firstName; // fullName is "Hopper, Grace" How to concatenate string variables with the += operator var firstName = "Grace", lastName = "Hopper"; var fullName = lastName; // fullName is "Hopper" fullName += ", "; // fullName is "Hopper, " fullName += firstName; // fullName is "Hopper, Grace"
  • 37. How to concatenate a string and a number with the + operator Murach's JavaScript and jQuery (3rd Ed.) © 2017, Mike Murach & Associates, Inc. C2, Slide 37 var months = 120; var message = "Months: "; message = message + months; // message is "Months: 120" How to concatenate a string and a number with the += operator var months = 120; var message = "Months: "; message += months; // message is "Months: 120"
  • 38. Some of the escape sequences that can be used in strings Murach's JavaScript and jQuery (3rd Ed.) © 2017, Mike Murach & Associates, Inc. C2, Slide 38 Operator Description n Starts a new line in a string. " Puts a double quotation mark in a string. ' Puts a single quotation mark in a string. How escape sequences can be used in a string var message = "A valid variable namencannot start with a number."; var message = "This isn't the right way to do this.";
  • 39. Terms related to strings Murach's JavaScript and jQuery (3rd Ed.) © 2017, Mike Murach & Associates, Inc. C2, Slide 39  concatenate (join) strings  concatenation operators  string expression  escape sequences
  • 40. Common methods of the window object Murach's JavaScript and jQuery (3rd Ed.) © 2017, Mike Murach & Associates, Inc. C2, Slide 40 alert(string) prompt(string, default) print() The syntax for calling a method of an object objectName.methodName(parameters) A statement that calls the alert() method of the window object window.alert("This is a test of the alert method");
  • 41. A statement that calls the prompt() method with the object name omitted Murach's JavaScript and jQuery (3rd Ed.) © 2017, Mike Murach & Associates, Inc. C2, Slide 41 var userEntry = prompt("This is a test of the prompt method", 100); The prompt dialog box that’s displayed
  • 42. One property of the window object Murach's JavaScript and jQuery (3rd Ed.) © 2017, Mike Murach & Associates, Inc. C2, Slide 42 location The syntax for accessing a property of an object objectName.propertyName A statement that displays the URL of the current page alert(window.location);
  • 43. Two methods of the window object Murach's JavaScript and jQuery (3rd Ed.) © 2017, Mike Murach & Associates, Inc. C2, Slide 43 parseInt(string) parseFloat(string) The parsing that’s done by the parse methods  Only the first number in the string is returned.  Leading and trailing spaces are removed.  If the first character cannot be converted to a number, NaN is returned.
  • 44. Examples that use the parseInt() and parseFloat() methods Murach's JavaScript and jQuery (3rd Ed.) © 2017, Mike Murach & Associates, Inc. C2, Slide 44 var entryA = prompt("Enter any value", 12345.6789); alert(entryA); // displays 12345.6789 entryA = parseInt(entryA); alert(entryA); // displays 12345 var entryB = prompt("Enter any value", 12345.6789); alert(entryB); // displays 12345.6789 entryB = parseFloat(entryB); alert(entryB); // displays 12345.6789 var entryC = prompt("Enter any value", "Hello"); alert(entryC); // displays Hello entryC = parseInt(entryC); alert(entryC); // displays NaN
  • 45. The same examples with the parse methods embedded in the alert() method Murach's JavaScript and jQuery (3rd Ed.) © 2017, Mike Murach & Associates, Inc. C2, Slide 45 var entryA = prompt("Enter any value", 12345.6789); alert(entryA); // displays 12345.6789 alert(parseInt(entryA)); // displays 12345 var entryB = prompt("Enter any value", 12345.6789); alert(entryB); // displays 12345.6789 alert(parseFloat(entryB)); // displays 12345.6789 var entryC = prompt("Enter any value", "Hello"); alert(entryC); // displays Hello alert(parseInt(entryC)); // displays NaN
  • 46. Two methods of the document object Murach's JavaScript and jQuery (3rd Ed.) © 2017, Mike Murach & Associates, Inc. C2, Slide 46 write(string) writeln(string)
  • 47. Examples of the write() and writeln() methods Murach's JavaScript and jQuery (3rd Ed.) © 2017, Mike Murach & Associates, Inc. C2, Slide 47 <body> <script> var today = new Date(); document.write("<h1>Welcome to our site!</h1>"); document.write("Today is "); document.write(today.toDateString()); document.write("<br>"); document.writeln("Today is "); document.writeln(today.toDateString()); document.write("<br>"); </script> <script> document.writeln("Welcome to our site!"); document.writeln("Today is Monday."); </script> <script> document.writeln("<pre>Welcome to our site!"); document.writeln("Today is Monday.</pre>"); </script> </body>
  • 48. The output in a browser Murach's JavaScript and jQuery (3rd Ed.) © 2017, Mike Murach & Associates, Inc. C2, Slide 48
  • 49. Terms related to objects Murach's JavaScript and jQuery (3rd Ed.) © 2017, Mike Murach & Associates, Inc. C2, Slide 49  object  method  property  call a method  parameter  window object  global object  dot operator  document object
  • 50. The Calculate MPG application Murach's JavaScript and jQuery (3rd Ed.) © 2017, Mike Murach & Associates, Inc. C2, Slide 50 The first prompt dialog box The second prompt dialog box
  • 51. The Calculate MPG application (continued) Murach's JavaScript and jQuery (3rd Ed.) © 2017, Mike Murach & Associates, Inc. C2, Slide 51 The alert dialog box that displays the result
  • 52. The HTML and JavaScript for the application Murach's JavaScript and jQuery (3rd Ed.) © 2017, Mike Murach & Associates, Inc. C2, Slide 52 <html> <head> <title>The Calculate MPG Application</title> <script> var miles = prompt("Enter miles driven"); miles = parseFloat(miles); var gallons = prompt("Enter gallons of gas used"); gallons = parseFloat(gallons); var mpg = miles/gallons; mpg = parseInt(mpg); alert("Miles per gallon = " + mpg); </script> </head> <body> <!-- Will show after the JavaScript has run --> <h1>Thanks for using the Miles Per Gallon application!</h1> </body> </html>
  • 53. The results of the Test Scores application in a browser Murach's JavaScript and jQuery (3rd Ed.) © 2017, Mike Murach & Associates, Inc. C2, Slide 53
  • 54. The HTML and JavaScript for the application Murach's JavaScript and jQuery (3rd Ed.) © 2017, Mike Murach & Associates, Inc. C2, Slide 54 <html> <head> <title>Average Test Scores</title> <script> var entry; var average; var total = 0; //get 3 scores from user and add them together entry = prompt("Enter test score"); entry = parseInt(entry); var score1 = entry; total = total + score1; entry = prompt("Enter test score"); entry = parseInt(entry); var score2 = entry; total = total + score2;
  • 55. The HTML and JavaScript (cont.) Murach's JavaScript and jQuery (3rd Ed.) © 2017, Mike Murach & Associates, Inc. C2, Slide 55 entry = prompt("Enter test score"); entry = parseInt(entry); var score3 = entry; total = total + score3; //calculate the average average = parseInt(total/3); </script> </head> <body> <script> document.write("<h1>The Test Scores App</h1>"); document.write("Score 1 = " + score1 + "<br>" + "Score 2 = " + score2 + "<br>" + "Score 3 = " + score3 + "<br><br>" + "Average score = " + average + "<br><br>"); </script> Thanks for using the Test Scores application! </body> </html>
  • 56. Exercise 2-1 Modify the MPG application Murach's JavaScript and jQuery (3rd Ed.) © 2017, Mike Murach & Associates, Inc. C2, Slide 56 Display the output in the browser, not in an alert dialog box.
  • 57. Exercise 2-3 Create a simple application Murach's JavaScript and jQuery (3rd Ed.) © 2017, Mike Murach & Associates, Inc. C2, Slide 57 Start with the MPG app and change it into a new app.
  • 58. Extra 2-1 Convert Fahrenheit to Celsius Murach's JavaScript and jQuery (3rd Ed.) © 2017, Mike Murach & Associates, Inc. C2, Slide 58 The prompt dialog box The alert dialog box To convert F to C subtract 32 from F and multiply by 5/9.
  • 59. Short 2-1 Modify the Test Scores application Murach's JavaScript and jQuery (3rd Ed.) © 2017, Mike Murach & Associates, Inc. C2, Slide 59 Estimated time: 10 to 20 minutes. Provide for a fourth score and display the results in a dialog box.