300 likes | 481 Views
CSS, Programming Intro. Week 4 INFM 603. Agenda. JavaScript Intro. Links. http://www.i-programmer.info/bookreviews/6-graphics/5444-html5-canvas-and-css3-graphics-primer-. html. JavaScript. JavaScript programming language that can appear in html pages It allow us to:
E N D
CSS, Programming Intro Week 4 INFM 603
Agenda • JavaScript Intro
Links • http://www.i-programmer.info/bookreviews/6-graphics/5444-html5-canvas-and-css3-graphics-primer-.html
JavaScript • JavaScriptprogramming language that can appear in html pages • It allow us to: • To dynamically create web pages • To control a browser application • Open and create new browser windows • Download and display contents of any URL • To interact with the user • Ability to interact with HTML forms • Process values provided by checkbox, text, buttons, etc. • JavaScript is not Java, however … • JavaScript constructs are similar to Java’s constructs (in many cases identical) • JavaScript can interact with java programs • Example: SqrTable.html • We will go over the details of this example later on
JavaScript • JavaScript Interpreter Process JavaScript code • To write JavaScript programs you need • A web browser • A text editor • A JavaScript program can appear • In a file by itself typically named with the extension .js • In html files between a <script> and </script> tags • Client-Side JavaScript the result of embedding a JavaScript interpreter in a web browser • Template for JavaScript Programs • Example: TemplateJS.html
Execution of JavaScript Programs • HTML parser Takes care of processing an html document • JavaScript interpreter Takes care of processing JavaScript code • HTML parser must stop processing an html file when JavaScript code is found (JavaScript interpreter will then be running) • This implies a page with JavaScript code that is computationally intensive can take a long time to load
JavaScript • Let’s go over several basic constructs that allow us to define JavaScript programs • Some definitions • string Any set of characters in double quotes (“ “) • function/method • An entity that completes a particular task for us • It may take values necessary to complete the particular task • It can return values • Generating output with the document.writeln method • Allow us to add text to the html file (Example: Writeln.html) by providing the required text in “ “ • You can specify html code and results of JavaScript constructs
JavaScript • Example: Date.html • Illustrates how we can generate HMTL output • Notice how we can use Date() to specify a particular date format Date() is part of JavaScript • The + allow us to concatenate strings • Example: “Mary” + “Land” “MaryLand” • Example: “Time is: “ + new Date()
Variables • Variable – A memory location that can store a value. In JavaScript variables are declared using var var temperature; • Variables names must start with a letter, underscore or dollar sign and can be followed by any number of letters, underscores, dollar signs or digits • Variables must be declared before they are used • A variable can hold different type of values • Values we can assign to variables • Integer – 0, 10, 40, 6, -7 • Floating-point – 3.2, .67, 1.48E-20 • String literals – “hello”, “goodbye” • Operators • Assignment operator (=) • Typical arithmetic operators (+, -, *, /) • Example: Variables.html
Reserved Words • Reserved words – words you cannot use as identifiers • Some of them are: • break • do • if • catch
Spaces, Semicolons, and Comments • JavaScript ignores spaces, tabs, and newlines between tokens • Use spaces to create nicely indented code • The rules are usually one tab for indentation or three spaces. You need to satisfy this requirement in programming assignments • A semicolon is generally used to mark the end of a statement and is optional when a statement appears on a separate line. For example, the following two set of statements are equivalent x = 1; y = 2; x = 1 y = 2 • In this course we will always use a semicolon to mark the end of a statement
Comments • Comments in JavaScript • Used to provide information to the programmer • Used to identify sections in your code • Ignored by the JavaScript interpreter • Two types of comments • Inline comment // This is a comment until the end of the line • Block comment /* The following is a comment that spans several lines */ • We can use a block comment for a single-line comment
Dialog Boxes • We can perform input and output via dialog boxes • Input via prompt • Example: InputOutput.html • Notice we can define several variables at the same time • prompt is a function that displays a dialog box with the specified title. It can be used to read any data • You can read numbers and strings via prompt • prompt-returns a string. • If you need to perform some mathematical computation you might need to explicitly convert the value read it into a number
Strings • You can use single or double quotes for strings (we will use double) • You can determine the number of characters in a string by accessing the length value var s = “Hello”; var x = s.length; • Some functions you can use with strings: • toLowerCase() • toUpperCase()
Conversions • In JavaScript you don’t specify the type of variables • Most of the time implicit transformations will take care of transforming a value to the expected one • Example: var age = 10; var s = “John Age: “ + age; • Sometimes you might need to explicitly transform a value • Mechanism to transform values: • Converting number to string varstringValue = String(number); • Converting string to number • var number = Number(stringValue); • var number = parseInt(stringValue); • var number = parseFloat(stringValue); • Example: Conversions1.html, Conversions2.html
Math Functions/Constants • Math.abs() – Absolute value • Example: Math.abs(-10) • Math.max() – Maximum of two values • Example: Math.max(10, 20) • Math.sqrt() – Square root • Example: Math.sqrt(4) • Math.random() – Random value between 0 and less than 1 • Example: Math.random() • Constants • Math.PI – Mathematical constant pi
Boolean Type • We have seen integer, float, and string values • New type: boolean type • Assumes the value true or false. • Variable declaration and initialization var found = true; var attending = false;
JavaScript (Comparisons) • You can compare values by using the following operators • === → Returns true if the values are equal, false otherwise (e.g., x === y) • !== → Returns true if the values are different, false otherwise (e.g., x !== y) • == Not as strict as the previous equality operator • != Not as strict as the previous inequality operator • Relational Operators • < → Less than returns true if left value is less than right value (e.g., x < y) • > → Greater than • <= → Less than or equal • >= → Greater than or equal • Example: Comparison1.html, Comparison2.html
JavaScript (If Statement) • If statement – Control statement that allow us to make decisions • First Form if (expression) { statement // executed if expression is true } • Example: IfStm1.html • Second Form if (expression) { statement1 // executed if expression is true } else { statement2 // executed if expression is false } • { } not needed for single statement execution • Example: IfStm2.html
JavaScript (Logical Operators) • Used with comparison operators to create more complex expressions • Operators • Logical and (&&) – expr1 && expr2 • Expression is true if and only if both expressions are true otherwise is false • Example: LogicalOp1.html • Logical or (||) – expr1 || expr2 • Expression is false if and only if both expressions are false otherwise is true • Example: LogicalOp2.html • Logical Not (!) – !expr • Inverts the boolean value of the expression
Precedence/Associativity • Remember you can use parenthesis to impose a particular order for the evaluation of an expression.
Guide To Writing JavaScript Programs • http://www.cs.umd.edu/~nelson/classes/utilities/JavaScript/
Writing a program • How to start? • Check you can output data (e.g., print a message “Done”) • Develop your code incrementally • Add a little bit, make sure it works, and then move on • Check that values read are correct • Remember GIGO (Garbage In Garbage Out) • Keep backups each time you make significant progress • Let’s apply this idea to an example
Cascaded If Statement Idiom • You can combine if statements to handle different cases • This approach to organize if statements to handle different cases is called the Cascaded IfStatement • Cascaded If statement general form: If (expr1) { // Statement is executed if expr1 is true } else if (expr2) { // Statement is executed if expr2 is true } else if (expr3) { // Statement is executed if expr3 is true } else { // If none of the above expressions is true } • Let’s write the above statement using nested if/else • Notice it is not a special JavaScript statement • Once one of the cases is executed no other case will be executed • You do not need to enclose statements in { } if only one statement is executed • A sequential set of if() statements is not equivalent to a cascaded if statement • No semicolons after if (exprX) • Example: See CascadedIf.html
How to include “ in a String • We need to use \” “The team is called \“The Super Team\””
alert • We can use the alert function to display information and for debugging purposes • Let’s see an example • Notice what happens when printing “<br />” with the alert function
while Statement • while statementControl statement which allows JavaScript to repeat a set of statements • Basic Form while (expression) { statements (body) // executed as long as expression is true } • { } are not required if you need to execute only one statement • You can have other types of statements (including whiles) in a while • Example: SqrtTable.html • Let’s write the previous example, step by step, starting with a loop that prints numbers
Trace Tables • Mechanism to keep track of values in a program • Allows you to understand the program behavior • We could create a trace table for SqrtTable.html
Coding Example (Display Even Numbers) • Let’s write a program that displays the even numbers that exists between two provided values • We will need to use the % operator • You can use the % operator to map a large range to a smaller range • Example: assigning classmates to 4 chairs
Coding Example (Parking Permits) • Let’s write a program that assigns parking permits to students in a school • Freshman red • Junior green • Sophomore yellow • Other green • Let’s use toUpperCaseto the input