Cpan240 JavaScript Guest Lecture 2
Objectives JavaScript Operators –Calculation Conversions –Comparison Operators –Logical operators –Bitwise Operators –Special Operators Order of Precedence Using built-in function User-defined functions Reference versus Value Array Objects
JavaScript Operators Operators are used to handle variables. –Arithmetic operators, such as plus. –Comparisons operators, such as equals. –Logical operators, such as and. –Control operators, such as if. –Assignment and String operators. Operators are represented by mathematical symbols but in a few cases they are actual words.
The most common operators used in JavaScript Mathematical: Used to perform mathematical calculations. Comparison: Used to compare two values, variables or statements. Assignment: Used to assign values to variables. Logical: Used to compare two conditional statements to see if one or both are true. Bitwise: Used to perform logical operations on the binary ("bit") level. Special: Used for specific tasks, these operators can also help eliminate unnecessary code.
Mathematical Operators + Addition - Subtraction * Multiplication ⁄ Division % Modulus Divides one value by another and returns the remainder ++ Increment Adds 1 to a value -- Decrement Subtracts 1 from a value - Negation Changes the sign of the value
Calculation Conversions The following will return a string as there is no way to add a "non-number" to a number: var myNum=10; var noNum="13"; var theSum=myNum+noNum; alert(theSum); The result here would be 1013.
Calculation Conversions An integer added to a floating point number will result in a floating point number. JavaScript treats all numbers as floating point numbers. If you add 13 and , you will get a floating point number as the result:
What is the result? var newNum=11; var newNum2=2; var result=newNum%newNum2; alert(result);
Increment/Decrement Operator (++/--) If the operator is put before the value, it increases the value by 1, returns that value to the variable and then performs the rest of the operation: var theNum=4; alert(++theNum);
What is the result? var theNum=4; alert(theNum++); alert(theNum);
Increments Example var a = 10; // initialize a to 10 var x = 0; // initialize x to 0 x = a; // a = 10, so x = 10 x = ++a; // a becomes 11 before assignment, // so a = 11 and x becomes 11 x = a++; // a is still 11 before assignment, // so x = 11; then a becomes 12 x = a++;// a is still 12 before assignment, //so x = 12; then a becomes 13
Comparison Operators
==Returns true if both values are equal !=Returns true if both values are not equal === Strict Equals - returns true if both values are equal and are the same data type !==Strict Not Equal - returns true if both values are not equal or not the same data type
Comparison Operators > Greater Than >= Greater Than or Equal <Less Than <=Less Than or Equal
Examples 25 == 25 // ("25 is equal to 25") true 25 == "25" // ("25 is equal to 25, after it has been converted from a string to a number" [The JavaScript interpreter will convert the string "25" to a number, 25.] ) true 25 != 25 // ("25 is not equal to 25") false 25 != 34 // ("25 is not equal to 34") true 25 === 25 // ("25 is strictly equal to 25") true 25 === "25" // ("the number 25 is strictly equal to the string '25'" [In this case, the data type of the values is taken into account and is not converted.] ) false 25 !== "25" // ("the number 25 is strictly not equal to the string '25'") true
Comparing two strings When comparing two strings, JavaScript converts each character to its ASCII value. For instance, in ASCII code "A"=65 and "a"=97. So, "A" > "a" would be false while "a" > "A" would be true.
Assignment Operators Assign (=): x = y Add and Assign (+=): x += y means the same as x = x + y Subtract and Assign (-=): x -= y means the same as x = x - y Multiply and Assign (*=): x *= y means the same as x = x * y Divide and Assign (/=): x /= y means the same as x = x / y Modulus and Assign (%=): x %= y means the same as x = x % y
Logical (Boolean) Operators !NOTReturns false if its single value can be converted to true; otherwise returns true ||ORReturns true if either value is true &&ANDReturns true if both values are true
Bitwise Operators &Bitwise And ^Bitwise XOR"Exclusive OR": 0 XOR 0 = 0, 0 XOR 1 = 1, 1 XOR 0 = 1, 1 XOR 1 = 0 |Bitwise Or ~Bitwise Not <<Left Shift >>Right Shift >>>Zero Fill Right Shift For the most part, these are used in advanced scripts in context with Java applets.
Special Operators ?:Conditional - A type of if...else statement. A condition is placed before the (?) and a value is placed on each side of the (:),Comma- Used to process a series of expressions delete Delete - Deletes an object, property, or element from an array in In - Used to inspect the contents of a specified object
Special Operators instanceofInstanceof - Tests an object to see if it is of a specified object. newNew - Creates an instance of an object thisThis - Refers to the current object typeofTypeof - Identifies the type of value being evaluated voidVoid- Evaluates an expression without returning a value These operators are used for specific tasks and can help eliminate unnecessary code.
Order of Precedence ( ) - Calculations done from the inside to the outside. [ ] function() !Not (Boolean) ~Not (Bitwise) -Negation ++ Increment -- Decrement new typeof void delete
Order of Precedence * Multiplication ⁄Division %Modulus +Addition -Subtraction <<Left Shift (Bitwise) >Greater Than >>Right Shift (Bitwise) <Less Than <=Less Than or Equal To >=Greater Than or Equal To
Order of Precedence ==Equals !=Not Equal &And (Bitwise) ^XOR (Bitwise) |Or (Bitwise) &&And (Boolean) ||Or (Boolean) ?
Order of Precedence =Assign +=Add and Assign -=Subtract and Assign *=Multiply and Assign ⁄=Divide and Assign %=Modulus and Assign <<=Left Shift by Value (Bitwise) >>=Right Shift by Value (Bitwise) &=And by Value (Bitwise) ^=XOR by Value (Bitwise) |=Or by Value (Bitwise)
Sample Scripts
Mail.htm This script will hide your address from spammers but still allow your visitors to see it and click on it as a mailto link: <!-- var user = "lunderwood"; var site = "jupitermedia.com"; document.write(' '); document.write(user + + site + ' '); //-->
Mail.htm In the document.write method, we build the actual link by creating a string with the HTML element used for links, '<a href=\"mailto:‘. We use \ " escape sequence to print the double quote " on the page.
Paycheck.htm <!– var paycheck=2000; document.write(paycheck+" "); paycheck+=2000; document.write(paycheck+" "); paycheck=paycheck-500; document.write(paycheck+" "); paycheck=paycheck*0; document.write(paycheck+" "); paycheck=paycheck+500; document.write(paycheck+" "); paycheck-=80; document.write(paycheck+" "); //-->
While.htm <!– var count=0; while (count<10) { document.write(count + " "); count++; } //-->
JavaScript Functions
Using built-in function Date.htm Time-sensitive welcome –Direct insertion script –Predefined Date() object –If/Else control –Variables –Objects –Methods
Date.htm: Time-Sensitive Welcome In the next line, this web page says Good Morning, Good Afternoon, or Good Night to the user, depending on what time the browser's machine has. var d = new Date(); var h = d.getHours(); if (h < 12) document.write("Good Morning."); else if (h < 17) document.write("Good Afternoon."); else document.write("Good Evening.");
JavaScript user-defined functions A function is a set of statements used to perform a specific task.function Just as a variable is a "data container," a function is a "code container." When you create a function, you are in fact, creating a new JavaScript command that can be called from anywhere within the script.
JavaScript Functions Similar to Java functions, but –Header is somewhat different function name(param_list) Return type not specified (since JS has dynamic typing) Parameter types also not specified To allow this, function code should be in the section of the.html file.
JavaScript Functions Variables declared in a function are local to the function. Parameters are all value –No parameter type-checking –Numbers of formal and actual parameters do not have to correspond Extra actual parameters are ignored Extra formal parameters are undefined
Like a variable, a function must be declared first: function giveName() { code goes here; }
Calling a Function A function call can be placed in the section within the script or in the section. It can also be placed in an external file. A function can even be called from within another function, but the code must first be loaded into memory in order for it to be used.
Calling a function from within the Script_6.htm: <!– function readyMessage() { alert("Are you ready for this?"); } readyMessage(); //-->
Script_7.htm <!– function music() { var place="Delta"; var type="blues"; alert("I like " + place + " " + type + "."); } music(); //-->
Script_7.htm JavaScript interpreter checks to see if the function has been loaded into memory. In our example above, it's already loaded because it came before the function call.
Script_9.htm Let us put this code in the portion: <!– function greetVisitor() { var myName = prompt("Please enter your name.", ""); alert("Welcome " + myName + "!"); } //-->
Script_9.htm Then, add this link somewhere in the body of the page and click on it. Meaning that you can call the function from within a link.
Script_10.htm Here's one that provides a solution if a name is not entered. Place this in the portion: <!– function greetVisitor() { var myName = prompt("Please enter your name.", ""); if ( (myName == "") || (myName == null) ) { alert("Don't you even know your own name?"); } else { alert("Welcome " + myName + "!"); } } /-->
Script_10.htm Then, put this in the portion: <input type="button" value="Click for Greeting" onClick="greetVisitor();"
Script_11.htm A function with multiple parameters <!-- function sayHi(a,b,c) { alert("Say hello to " + a); } //--> <!-- sayHi("Bob","Carol","Ted") //-->
Script_12.htm <!-- function say(what) { var myName = prompt("Please enter your name.", ""); alert(what + myName); } //-->
Global Variables These are variables declared outside the function, within the overall script. If the value of a global variable is reassigned (changed) within a function, it will be reassigned throughout the entire script.
Local Variables In order to be declared locally they must be declared using the reserved word var. You can even use the same name as a global variable but its value will only be used within the function.
Last note on booleans In Java: –“boolean values are not integers, may not be treated as integers, and may never be cast to or from any other type” In JavaScript –in numeric context, true is cast to 1 and false is cast to 0 –in boolean context, defined values are cast to true, and undefined is cast to false –in string context, true is cast to “true” and false is cast to “false”
Primitive versus Reference Types What does it mean when we say "b = a" a = 1; b = a; b = 2; document.write(a, " ", b); g = {p1: "g1", p2: "g2"}; h= g; h.p1 = "b1"; document.write(g, " ", g.p1, " ", g.p2, " "); document.write(h, " ", h.p1, " ", h.p2, " "); e = "astring"; f= a; f = "bstring"; document.write(e, " ", f, " ");
Reference versus Value Primitive types (numbers, strings) are passed into a function by value (a copy is passed) a =1; b = a; means that a copy is made of a's contents and that copy is assigned to b
Reference versus Value Other types (arrays, objects) are passed by reference a = [1]; b = a; means that a "points" to the array b is given a copy of that address b[0] refers to exactly the same location as a[0] but reassigning b wipes out the copy of the address (meaning that a and b no longer point to the same thing, but that thing is not wiped out)
Array Objects JavaScript arrays are either just like Java arrays, or a special case of JavaScript objects where the properties are always integers 0, 1, 2,... Things to notice –array slot can hold anything (including other arrays or objects) –no pre-declared size –don’t have to fill it from beginning to end
Array Objects More relaxed version of Java arrays Size can be changed and data can be mixed Creating arrays Using the new operator and a constructor with multiple arguments var A = new Array("hello", 2, "you"); Using the new operator and a constructor with a single numeric argument var B = new Array(50); Using square brackets to make a literal var C = ["we", "can", 50, "mix", 3.5, "types"];
Examples a = [“first”, "second"]; for (i=0; i<2; i++) { document.write(a[i] + " "); } a = new Array(); a[1] = "something"; for (i=0; i<2; i++) { document.write(a[i] + " "); }
Array Objects Array Length Like in Java, length is an attribute of all array objects Unlike Java, length can be changed by the programmer Actual memory allocation is dynamic and occurs when necessary –An array with length = 1234 may in fact have memory allocated for only a few elements –When accessed, empty elements are undefined
Array Methods There are a number of predefined operations that you can do with arrays concat two arrays into one join array items into a single string (commas between) sort –Sort by default compares using alphabetical order –To sort using numbers we pass in a comparison function defining how the numbers will be compared reverse –Reverse the items in an array
Array Objects These operations are invoked via method calls. Also many, such as sort and reverse are mutators, affecting the array itself JavaScript also has 2-dimensional arrays –Created as arrays of arrays
Array_1.htm var x var mycars = new Array() mycars[0] = "Saab" mycars[1] = "Volvo" mycars[2] = "BMW" for (x in mycars) { document.write(mycars[x] + " ") }
ConcatArray.htm var arr = new Array(3) arr[0] = "Jani" arr[1] = "Tove" arr[2] = "Hege" var arr2 = new Array(3) arr2[0] = "John" arr2[1] = "Andy" arr2[2] = "Wendy" document.write(arr.concat(arr2))
JoinArray.htm var arr = new Array(3) arr[0] = "Jani" arr[1] = "Hege" arr[2] = "Stale" document.write(arr.join() + " ") document.write(arr.join("."))
Multiple Choice Questions 1. A data type is: a.a letter b.a number c.both 2. The four basic data types are: a.strings, numbers, BooBoos, and nulls b.strings, text, Booleans, and nulls c.strings, numbers, booleans, and nulls d.strings, numbers, Booleans, and zeros
Multiple Choice Questions 3. To display a backslash, using an escape sequence, it would be written: a./\ b.// c.|backslash d.\\ 4. A variable is used to store: a.an escape sequence b.hidden script c.data
True/False Questions 1.Comment tags are used to hide script from new browsers. 2.Variables cannot be used together with text strings. 3.A string cannot have more than one set of quotes. 4.HTML elements can be used inside of a string. 5.A null data type returns a zero. 6.Bob Dylan writes good music (I just wanted to make sure you were awake). 7.A variable must be declared and initialized all on the same line. 8.A variable name can begin with a number.
Summary: What was covered? JavaScript Operators –Calculation Conversions –Comparison Operators –Logical operators –Bitwise Operators –Special Operators Order of Precedence Using built-in function User-defined functions Reference versus Value Array Objects