JavaScript and Ajax (Expression and Operators) Week 3 Web site: http://fog.ccsf.edu/~hyip
Expression An expression is any valid set of literals, variables, operators, function calls Expression will evaluate to a single value Examples: 3 + 7 3 + 7 + 10 + "" "Dr." + " " + "Pepper" Literal is a “simple expression”: 1.7 // number literal "JS“ // string literal true // boolean literal null // special value {x:1, y:2} // object literal [2,4,6] // array literal function(x) { return x * x; } // function literal
Statement A statement is any set of declarations, method calls, function calls, and expressions that performs some action var num = 1; // variable declaration document.write("Hello"); // function call Statement end with (;) which is optional Statements often contain expressions that have to be evaluated before the specified action can be performed document.write("Sum of 3 and 7: ", 3 + 7, "<br>"); // function call with expression var total = 1 + 2; // assignment statement with expression
Compound Statements JavaScript has a way to combine a number of statements into a single statement (or statement block) { var a = 3; var b = 4; var result = 3 + 4; alert("Sum is: " + result); } This statement block acts as a single statement, it does not end with a semicolon. The primitive statements within the block end in semicolons, but the block itself does not
Operators Operators are the workers in expressions An unary operator performs work, or operates, on one operand A binary operator operates on two operands A ternary operator operates on three operands
Operators (continue…) var fname = ""; var myName; (fname.length == 0) ? myName = "unknown" : myName = fname; alert(myName); Operator Flavor Syntax Example Unary Operand operator Operator operand count++ -88 Binary Operand operator operand 7+8 num1 < num2 Ternary Operand operator operand operator opreand (cond)? exp1 : exp2; See below
Types of Operators JavaScript supports five categories of operators: String operator: operators that work on strings Arithmetic operators (or mathematical operators): operators that perform mathematical computations Assignment operators: operators that assign a value to a variable, object, or property Comparison operators: operators that compare two values or expressions and return a "boolean" value indicating true or false Logical operators (or boolean operators): operators that take boolean values as operands and return a boolean value indicating the true or false of the relationship In addition, JavaScript supports one special operator, the conditional operator [See operator sample]
String Operators There are only two string operators: The concatenation operator (+) The concatenation by value operator (+=) The concatenation operator (+) concatenates two strings together var num = 1; var result = "Hello, I have " + num + " dog."; alert(result); The concatenation by value (+=) concatenates the string on the right side to the string value stored in the variable on the left side, then assigns the result back to the left operand variable var myName = prompt("May I have your name?", ""); var greeting = "Hello "; greeting += myName; greeting += " welcome"; NOTE: a common use of the concatenation by value operator (+=) is to pile a bunch of HTML statements into a single string variable for easy writing to a pop-up window.
Arithmetic (Mathematical) Operators Arithmetic operators are operators that perform mathematical operations NOTE: all arithmetic operators work on numbers and result in a number. NOTE: division by zero results in the numeric value Infinity. (Some browsers result in undefined or NaN)
Arithmetic Operators (continue…)
Arithmetic Operators (continue…)
Assignment Operators Assignment operation either initializes or changes the contents of the variable listed on the left of the operator. var myCup = "lemonade"; myCup += " tea"; // "lemonade tea" myCup = "ice water";
Assignment Operators (continue…)
Comparison Operators Comparison operators compares two values or two expressions of any data type. Usually, the two items being compared are of the same data type. The result of a comparison is always a boolean value: true or false. JavaScript often performs conversions for you when you do comparisons of strings and numbers. All comparisons except (===) and (!==), JavaScript assumes you are trying to compare similar data type and performs the conversions for you. if (5 == "5") { alert("true"); } else { alert("false"); } NOTE: JavaScript converts the string to a number in order to perform a meaningful comparison. (numbers had already represented in float, so perform a parseFloat() to string)
Comparison Operators (continue…)
Comparison Operators (continue…)
Logical (Boolean) Operators Logical operations (aka Boolean operations) always result in a truth value: true or false. The && (AND) operator: In order for an && (AND) expression to be true, both operands must be true. The || (OR) operator: only one side needs to be true in order for the expression to evaluate to true. The ! (NOT) operator: negate the expression
Logical Operators (continue…)
Conditional Operator The conditional operator is the only JavaScript operator that takes three operands. The syntax is (condition) ? ValueIfTrue : ValueIfFalse ; var age = 38; status = (age >= 18) ? "adult" : "minor" ; NOTE: status = "adult" ("adult" will be assigned to the variable status.)
Conditional Operator (continue…) <html> <head><title>conditional operator</title> </head> <body> <h1>conditional operator</h1> <script language= "JavaScript" type= "text/javascript"> alert(parseInt(prompt("what is 100 + 50?", "")) == 150 ? "correct" : "wrong "); </script> </body> </html>
Special Operators JavaScript supports several special operators that you should be aware of: delete, new, this, typeof, and void delete operator: allows you to delete an array entry or an object from memory. delete is a unary operator that attempts to delete property, array element, or variable specified as its operand. Not all variables and properties can be deleted: built-in core and client-side properties, and user-defined variables declared with the var statement cannot be deleted. When remove an element from an array with the delete operator, JavaScript does not collapse the array. In stead, that array element becomes undefined; any attempt to evaluate that element results in undefined. The Object-Creation Operator (new): creates a new object and invokes a constructor function to initialize it. It is a unary operator.
Special Operators (continue…) The special keyword - this is a shortcut way of referring to the current object The typeof operator: is a unary operator that determines the current data type of any variable. typeof (operand) Or typeof operand The void operator: is a unary operator that tells the interpreter to evaluate an expression and returns no value (return undefined). [See sample program for this operator]
Functions A function is a block of predefined programming statements whose execution is deferred until the function is “called”. You call a function by invoking its name with any required or optional parameters. A function parameter, aka an argument, is a data value or data reference that you can pass to the function to work on or use. Function normally defined in <head> section: <head> <script language="JavaScript" type="text/javascript"> function greetVisit() { alert("Hello"); } </script> </head> Function normally called in the <body> section: <body> greetVisitor(); </body>
Functions (continue…) There are two ways to pass data to a function: Pass by value (when passing primitive data) Pass by reference (when passing composite data) Return data from function using return statement [See function sample]
The Order of Operations
The Order of Operations (continue…)
Exercise 4 + 10/2 * 3 – (1 + 2) * 4 = 7 7 + 5 + “dollars” = “12dollars” “dollars” + 7 + 5 = “dollars75” 6 + 25/5 = 11 4 + 10 – 5 + 2 = 11 4 + 5%3 + 7 = 13 2 * 4 * 8 – 6 * 2 = 52 5 * “4” = 20 4%2 * 98 = 0 2 * 4 + “5” = 85 “4” – 2 = 2