350 likes | 462 Views
CSC 3084: Web Development and Programming. Chapter 2: Getting Started with JavaScript. Chapter Overview. By the end of this chapter, you should be able to : Include JavaScript in the head of an HTML document .
E N D
CSC 3084:Web Development and Programming Chapter 2: Getting Started with JavaScript
Chapter Overview • By the end of this chapter, you should be able to: • Include JavaScript in the head of an HTML document. • Recognize the JavaScript syntax for identifiers, comments, methods calls, conditional expressions • Describe the prompt and alert methods. • Describe the three primitive data types used in JavaScript. • Write basic mathematical and logical expressions in JS. • Declare variables and assign them values. • Describe the parseInt and parseFloatmethods. • Describe the syntax for if, while and for statements.
Loading an External JavaScript File <script src="calculate_mpg.js"></script>
Embedded JavaScript <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>
JavaScript in the Body of a Web Page <p> <script> var today = new Date(); document.write("Current date: "); document.write(today.toDateString()); </script> </p> <p>© <script> var today = new Date(); document.write( today.getFullYear() ); </script> , San Joaquin Valley Town Hall </p>
JavaScript in the Body of a Web Page <p> <script> var today = new Date(); document.write("Current date: "); document.write(today.toDateString()); </script> </p> <p>© <script> var today = new Date(); document.write( today.getFullYear() ); </script> , San Joaquin Valley Town Hall </p>
The noscript Element • A noscript element in the body of the HTML: <p>© <script> var today = new Date(); document.write( today.getFullYear() ); </script> <noscript>2012</noscript> , San Joaquin Valley Town Hall </p>
The noscript Element • A noscript element at the start of the HTML: <h2> <noscript> To get the most from this web site, please enable JavaScript. </noscript> </h2>
Basic Syntax Rules for JavaScript • JavaScript is case-sensitive. • JavaScript ignores extra whitespace within statements. • Each JavaScript statement ends with a semicolon. • Split a statement after: • an arithmetic or relational operator • an opening brace, bracket, or parenthesis • a closing brace • Do not split a statement after: • an identifier, a value, or the returnkeyword • a closing bracket or parenthesis
Terms You Should Already Know • statement • whitespace • identifier • camel casing • comment • comment out (i.e., disable code by wrapping it with a comment)
Rules for Creating Identifiers • 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. (We’ll learn about these later on.)
Valid identifiers in JavaScript subtotal index_1 $ taxRate calculate_click $log
Camel Casing Versus Underscore Notation taxRatetax_rate calculateClickcalculate_click emailAddressemail_address firstNamefirst_name futureValuefuture_value • Use whichever style you want, but be consistent • Your book uses camel notation for JavaScript identifiers and underscore notation for HTML elements • Pick meaningful identifier names and don’t use cryptic abbreviations
JavaScript Comments • Block comments begin with /* and end with */. • Single-line comments begin with two forward slashes and continue to the end of the line. • HTML comments are written like this:<!-- This is a comment --> • CSS comments are written using the /* */ notation.
The window Object • The window object is a data structure available in all JavaScript applications • It has methods like alert, prompt and print • The methods can be called through the window object (i.e., window.alert()) or without the object (i.e., alert()) because it is a global object
Common Methods of the window Object • alert(string) Displays a dialog box that contains the string argument. • prompt(string, Displays a dialog box containingdefault) the first string argument and the default value as a suggested response to the prompt. • print()Issues a print request to the browser, which displays a message in a box.
Examples of window Methods window.alert("This is a test of the alert method"); varuserEntry= prompt("This is a test of the prompt method", 100);
The location Property • The location property of the window object provides the URL of the current web page • alert(window.location);
Terms Related to Objects You Should Now Know • object • method • call a method • window object • global object • dot operator
Data Types: number, string and Boolean • Examples of number values: 15, -21, 21.5, -124.82, -3.7e-9 • Examples of string values: "JavaScript“, 'String Data‘, "" • The two Boolean values: true, false • 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, respectively
Common Arithmetic Operators Operator Example Result + 5 + 7 12 - 5 - 12 -7 * 6 * 7 42 / 13 / 4 3.25 % 13 % 4 1 ++counter++ adds 1 to counter --counter-- subtracts 1 from counter • All numbers are stored as floats, so there is no integer division in JavaScript • / and % perform floating-point division
Declaring and Using Variables • var subtotal; • var investment, interestRate, years; • var subtotal = 74.00; • varsalesTax = subtotal * .1; • JavaScript also has the compound assignment operators like +=, *=, etc. • += performs addition if the variable stores a number, and performs concatenation if the variable is a string
More on Strings and Booleans • Escape sequences: \n \” \’ • + can be used for concatenation • varfirstName = "Ray", lastName = "Harris"; • varfullName = lastName + ", " + firstName; • If a string and a number are combined with +, the number is converted to a string and concatenation is performed • Boolean variable: varisValid = false;
Methods of the window Object for Converting String Values • parseInt(string)Converts the string argument into an integer. • parseFloat(string)Converts the string argument into a float. • If the conversion process in either case is not successful, the method returns NaN (Not a Number) • You can check if a value is NaN using the isNan(x) method var age = prompt(“Enter your age:”) age = parseInt(age); var age = parseInt(prompt(“Enter your age:”));
The Relational Operators Operator Description Example == EquallastName== "Harris"testScore== 10 != Not equal firstName!= "Ray"months != 0 < Less than age < 18 <= Less than or equal investment <= 0 > Greater than testScore> 100 >= Greater than or equal rate / 100 >= 0.1
The Logical Operators in Order of Precedence Operator Description Example ! NOT!isNaN(age) && ANDage > 17 && score < 70 || ORisNaN(rate) || rate < 0
If-statements if ( isNaN(userEntry) || userEntry <= 0 ) { alert ("Please enter a valid number > zero."); } if ( isNaN(rate) ) { alert ("You did not provide a number for the rate."); } else if ( rate < 0 ) { alert ("The rate may not be less than zero."); } else if ( rate > 12 ) { alert ("The rate may not be greater than 12."); } else { alert ("The rate is: " + rate + "."); }
While-loop Example varsumOfNumbers = 0; varnumberOfLoops = 5; var counter = 1; while (counter <= numberOfLoops) { sumOfNumbers += counter; counter++; } alert(sumOfNumbers);
While-loop Example var total = 0, count = 0, number; number = parseFloat( prompt("Enter a number:") ); while ( !isNaN(number) ) { total += number; count++; number = parseFloat( prompt("Enter another number " + "or click Cancel to stop:") ); } var average = total / count; alert("The average is: " + average);
Do-loop Example varsumOfNumbers = 0; varnumberOfLoops = 5; var counter = 1; do { sumOfNumbers += counter; counter++; } while (counter <= numberOfLoops); alert(sumOfNumbers);
For-loop Example varsumOfNumbers = 0; varnumberOfLoops = 5; for (var counter=1; counter <= numberOfLoops; counter++ ) { sumOfNumbers += counter; } alert(sumOfNumbers);
For-loop Example varinvestment = 10000; varannualRate = 7.0; var years = 10; varfutureValue = investment; for (vari = 1; i <= years; i++) { futureValue += futureValue * annualRate / 100; } alert (futureValue);
MPG Calculator • See JS Textbook Files\book_apps\ch02\mpg.html
Test Average Calculator • See JS Textbook Files\book_apps\ch02\test_scores.html
Error Console • Debugging JavaScript needs to be done through the browser, so the browser’s error console is a helpful tool • In Firefox, hit F12 to open Firebug (or Ctrl+Shift+J to open the built-in console) • In Chrome, hit Ctrl+Shift+I