learn more...Assignment OperatorsThe key assignment operator is the equals sign (=). The left operand is a variable, an array element, or an object property, and the right operand is either a literal or another variable, array element, or object property. Assigning a variable a value can be accomplished with any number of different combinations of variables, array elements, object properties, and literals. The following provides an idea of the range of assignments: alpha= 77; alpha= (fishSize.length / 2); alpha= (beta > gamma); Compound OperatorsOperators that include assignment along with an operation are compound operators. These operators work as a shorthand for an assignment plus another operation. For example: var bankAccount += interest; is equivalent to writing var bankAccount = bankAccount + interest; Besides addition, compound operators in JavaScript include subtract assign (-=), multiply assign (*=), divide assign (/=), and modulo assign (%=). For example, the following script uses the modulo compound assignment operator: <html>
<head>
<script language="JavaScript">
var bolts=150, lot= 60;
bolts %= lot;
document.write("Odd lot=" + bolts);
</script>
</head>
<body bgcolor="lightslategray">
</body>
</html>
The example shows how two operations can be combined into a single one. The variable bolts is divided by the value of the variable lot, and the remainder (modulo) is assigned to the variable bolts. It would be the same as writing this: var bolts = bolts % lot; However, instead of taking two operations, one does the trick of assignment and operation. Comparison OperatorsProbably the area of most mistakes in JavaScript with operators is confusing (or just forgetting) the difference between assignment operators and comparison operators. Assignment operators equate a value with a variable, array element, or object property. Comparison operators generate a Boolean value. For example, the following script returns a false Boolean value: <html> <script language="JavaScript"> var wrong= (6==7) document.write(wrong); </script> <body bgcolor="lightslategray"> </body> </html> The comparison operator is the double equals sign (= =), and the assignment operator is the equals (=) sign. The most common problem is in a standard conditional statement where the developer types this: if (alpha = beta) { .... WRONG
when he meant to type this: if (alpha==beta) { .... RIGHT
In the debugging process, one of the first things to look for is the placement of an assignment operator where an equality operator should be. The other comparison operators include not equal to (!=) less than (<), greater than (>), less than or equal to (<=), and greater than or equal to (>=). Like the equality operator, these other comparison operators have two roles. One role is part of a conditional statement, and the other is to serve as Boolean literals in definitions as the previous example showed. The following script shows how variables can be defined so that they can contain Boolean literals and then used as part of a conditional statement without the use of comparison operators: <html>
<script language="JavaScript">
var alpha=25;
var beta=35;
var zeta=(alpha <= beta);
if(zeta) {
var sigma ="This is true."
} else {
var sigma = "This is not true.";
}
document.write(sigma);
</script>
<body bgcolor="lightslategray">
</body>
</html>
In the script, the variable alpha is compared to be less than or equal to (<=) beta in the definition of zeta. Because alpha is less than beta, the variable zeta contains a Boolean value of true. In the conditional statement, no comparative operators are used because the variable beta is already a Boolean value. Because the value is true, it meets the condition to load the variable sigma with the message "This is true." Strict Equality OperatorsJavaScript 1.3 introduced strict equality and inequality operators. These operators test for both equality of value and equality of type. In other words, if both values were 23 but one variable is a string and the other is a number, you might think that they would be unequal anyway. Consider the following script: <html> <script language="JavaScript"> var currentWord="75"; var currentNumber=75; var outcome=(currentWord==currentNumber); document.write(outcome); </script> <body bgcolor="lightsalmon"> </body> </html> You might be surprised to find that the variable outcome is true ! The reason for that is that JavaScript tries very hard to resolve numeric and string differences. Remember, if you define a variable as follows, the outcome is a string even though the line mixes numeric and string literals: var mix = "$" + 12.33; The same is true when JavaScript compares two variables where one is a number and one is a string. If the "values" are deemed to be the same even though one is a string and the other is a number, JavaScript helpfully makes them equal, as was seen in the previous script. However, if you had an application where both the values and the type of data are important to compare, you could not make that comparison with standard comparison operators. To fix that problem, JavaScript 1.3 introduced strict equality (===) and inequality (! ==) operators. These operators look at not only the values, but also at the type of variable. In the previous script, change this line: var outcome= (currentWord==currentNumber); to var outcome= (currentWord===currentNumber); Then save the script and run the program again. In the second version of the script, the outcome changes to false. While the numbers are the same, the data types are different. To get a true outcome, change the line to the following: var outcome= (currentWord! ==currentNumber); Both Netscape Navigator 4.7 and Internet Explorer 5 and later recognize strict equality and inequality operators. (Version 4 of Netscape Navigator requires language=JavaScript1.2 in the <SCRIPT> tag, but in later versions of the browser, all you need is language=JavaScript.) Arithmetic OperatorsThe basic arithmetic operators in JavaScript are fairly self-explanatory, with a few exceptions. To avoid the few aggravations from these exceptions, each operator is discussed with a focus on uses. Add and Concatenate (+)One arithmetic operator that has two different uses is add (+). First, the add operator adds values in math operations. Second, it concatenates (joins) strings or strings and other literals. Mathematical addition is fairly straightforward, but concatenation is not. When the add operation joins a string and a number, it concatenates them and converts the number into a string. For example, the following script joins strings with nonstring literals: <html> <head> <title>Add and Concatenate</title> <script language="JavaScript"> var Boole= 22 < 90; var string="250"; var numnum=88; var BooleNum =Boole + numnum; var BooleString=Boole + string; var StringNum=string + numnum; var part1="Boolean value <b>" + Boole + "</b> plus the number " + numnum + " = " + Subtract and Negation (-)The minus sign (-) has two very different uses. First, in arithmetic operations, the subtract operator subtracts the second operand from the first. Hence, this line places the value 7 in the variable alpha: var alpha = 10-3; Second, used as a unary operator, the minus sign changes a positive value to a negative value. Moreover, if a negative value is subtracted from a positive value, the result is the same as adding two positive values. The following script illustrates using both the unary negation and subtraction with the minus (-) sign as an operator. For example, try out the following script and see if you can determine ahead of time what the outcome will be: <html> <head> <title>Minus sign and negative values</title> <script language="JavaScript"> var posVal=44; var negVal= -posVal; var diffVal = (posVal-negVal); document.write(diffVal); </script> </head> <body bgcolor="papayawhip"> </body> </html> If you guessed that the output on the screen would be 88, you are right. The positive value in the variable posVal is 44. The variable negVal is created by the unary negation of posVal. When negVal is subtracted from posVal, the effect is to add the two values. (Just as in grammar, a double-negative creates a positive.) Multiply (*)The multiplication operator is simple-it multiplies two numbers. However, if you attempt to multiply two strings containing numeric characters, JavaScript attempts to change the strings into numbers and complete the multiplication. For example, try the following script: <html> <head> <title>Multiply Numbers in Strings</title> <script language="JavaScript"> var stringNum="5"; var stringNum2="20"; var mulEm= stringNum * stringNum2; document.write(mulEm); </script> </head> <body bgcolor="peru"> </body> </html> The output to the screen will be 100. So, the multiply operator (*) can actually convert certain strings into numbers as well as multiply numbers. Divide (/)Like the multiply operator, the divide operator (/) works with numbers. In operation, the left operand is divided by the right operand. Also, like the multiply operator, the divide operator attempts to convert a string into a number. The area where division differs most from the other operations is in a divide by zero error. Two different types of returns result. A divide by zero of a number other than 0 results in Infinity, while zero divided by zero returns NaN. The following script demonstrates what returns from both types of divide by zero errors. Also, the script shows how to use the built-in functions isFinite() and isNaN() to test for Infinity and NaN values. In the case of Infinity, the isFinite() function must be negated using the ! operator. For a designer, the importance of knowing when a divide by zero instance occurs is so that you can keep it from crashing your program. A home-decorating site, for example, has a module that calculates the amount of paint required to paint rooms. A gallon of paint covers 350 square feet. So, somewhere in the calculator, the designer must have a formula that divides 350 by the square feet of the room being painted. Suppose that the viewer forgot to enter a value for the square feet of the room and the script attempted to divide 350 by 0. Rather than sending the viewer into confusion by telling her that she had to purchase an infinite number of gallons of paint, you can trap to divide by zero errors and send any message that you want, as the following script illustrates: <html>
<head>
<title>Divide by Zero Errors</title>
<script language="JavaScript">
var leftOperand=77;
var rightOperand= 20 > 30;
var divEm= leftOperand / rightOperand;
var nada= 0/0;
document.write(divEm + "<p>" + nada);
if(!isFinite(divEm)) {
alert("Whoa Dude that\'s a big number!")
}
if(isNaN(nada)) {
alert("You are dividing nothing by nothing.")
}
</script>
</head>
<body bgcolor="springgreen">
</body>
</html>
Modulo (%)The modulo (%) operator returns the remainder in a division operation. The left operand is divided by the right operand, and only the remainder is returned. While the modulo operator does not come to mind in most applications, it can prove to be an extremely useful operator. For example, the following script uses the operator to convert long decimal places into two-place decimals. modulo2dec.html<html>
<head>
<title>Modulo two decimal place converter</title>
<style>
body {
background-color: plum;
font-family: verdana;
font-weight: bold;
}
</style>
<script language="JavaScript">
var dec=.06;
var part=77.4;
part += (dec * part);
var wholeInt=Math.floor(part);
//The Math.floor() function rounds the variable 'part' down to the nearest whole integer.
//Prior to obtaining the modulo (remainder) 'part' times 100 is rounded down to the
Increment (++) and Decrement (- -) OperatorsThese operators either add 1 or subtract 1 from an operand. In examples where loops have been used, the counter variable typically increments or decrements using these two operators. This general form in a loop statement is the most common usage of the increment or decrement operator: for (counter=0; counter<20; counter++) {....
The operand connected with these two operators can be preaffected or postaffected. If the operator is in front of the operand, the value is added or subtracted before the next operation. If the operator is at the end of the operand, the addition or subtraction comes after the operation. For example, the following script can be used to show how each affects the operand: <html>
<head>
<title>Increment/Decrement operator</title>
<script language="JavaScript">
var combine="";
var bounce=0;
for (var counter=0;counter <=5; counter++) {
var Hep=bounce++;
combine += "Hep value =" + Hep + "<br>";
}
document.write(combine);
</script>
</head>
<body bgcolor="palevioletred">
<center>
</body>
</html>
When you run the script, the outcome on the screen is as follows: Hep value =0 Hep value =1 Hep value =2 Hep value =3 Hep value =4 Hep value =5 The first time through the loop, the variable bounce, originally declared with a value of zero (0), remained zero because the increment in its value is after the definition of the variable Hep. Now change the position of the increment operator to the front of the variable, changing the line to this: var Hep= ++bounce; Now the output shows this: Hep value =1 Hep value =2 Hep value =3 Hep value =4 Hep value =5 Hep value =6 As can be seen, the position of the increment operator made a fundamental change in the output. With the increment operator in front of the operand, the Hep variable was incremented in the first iteration, but it wasn't until the second iteration that the Hep variable changed when the operator was at the end of the operand. A small change in the code led to a big change in the output. With increment and decrement operators, you must be especially vigilant not to crash a program because the position of the operator is positioned incorrectly. Operators in the Context of Using String Variables and LiteralsAs you saw when using the plus (+) operator, numbers can be added or strings and numbers can be concatenated into a single string. So, the idea of a "string operator" is very much a context-dependent concept. Besides using the plus (+) operator, you can use the comparison operators (>, >=, <, <=, ==, !=) with strings. In using comparison operators, the operator compares the string operands in an alphabetical order based on Unicode character encoding. The higher in the alphabet the character is, the greater the character is in comparison with another character. However, uppercase letters are less than lowercase letters. Therefore, Xray is less than emergency, as far as JavaScript is concerned. The following script shows some relationships between order and uppercase and lowercase strings. stringOps.html<html> <head> <title>String comparisons</title> <script language="JavaScript"> var alpha="apples"; var beta="oranges"; var gamma="Apples"; var delta="Oranges"; var lclc=beta > alpha; var lcuc=alpha > gamma; var uclc=gamma > alpha; var banner="<h3>String comparisons</h3>" var first=beta + " greater than "+ alpha + " results in " + lclc + "<p>"; var second=alpha + " greater than "+ gamma + " results in " + lcuc + "<p>"; var third=delta + " greater than "+ alpha + " results in " + uclc; document.write(banner+first+second+third); </script> </head> <body bgcolor="mistyrose"> </body> </html> When comparing strings with numbers, a different outcome occurs than when using the plus (+) operator. Instead of turning numbers into strings, JavaScript attempts to turn strings into numbers when making comparisons that involve numeric characters in strings. For example, if you write the following, the variable alpha would be true: var alpha="10" > 3; However, a string with a number followed by character letters does not ignore the letters and make a valid numeric comparison with a numeric operand. TIP Whenever you're not sure about what is greater than or less than some combination of numbers, numbers and strings, or strings and strings, use your browser address window as a test bench. Just enter the word javascript:, followed by the operands and operators. Boolean OperatorsThe comparison operators result in Boolean outcomes, but three logical operators in JavaScript can be considered Boolean as well. The operators combine different conditions or the negation of a condition. Logical AND (&&)A common requirement in a script is for two different conditions to exist for an outcome to be true or false. JavaScript provides the logical AND (&&) operator to determine whether two or more conditions are met. For example, an array search might seek to find all instances of customers who are interested in purchasing a new printer and who live in the state of Iowa so that they can be contacted for a printer trade show in Des Moines. Only if both conditions are true will the outcome be true and added to a contact list. For example, the following script segment searches for two conditions in an array: for (var seek=0;customers.length;seek++)
if((interest[seek]=="printer") && (state[seek] =="Iowa")) {....
Note that a double set of parentheses have to enclose the script within the if statement. You may also use the logical AND in defining variables. For example, in the following script, the first variable evaluates to true and the second evaluates to false: <html>
<head>
<title>String comparisons</title>
<script language="JavaScript">
var alpha = (15 < 20) && ("pen" > "Sword");
var beta = ("big" > "tall") && (20 < 30);
document.write(alpha + "<br>" + beta)
</script>
</head>
<body bgcolor="lightcoral">
</body>
</html>
Logical OR (||)The logical OR operator (||) uses the double pipes as a symbol. When two or more conditions are stated using the logical OR operator, only one of the conditions need be met for the outcome to evaluate as true. For example, the variable alpha in the following would evaluate to true, even though two of the conditions are false: var alpha = (56 < 34) || (10 > 2) || ("Fred" > "Alice");
You may also use the logical OR (or the logical AND) with variables defined with Boolean values. For example, the following lines show how you might use the logical OR in a script: var alpha = ("beans" > "Potatoes");
var beta = 30 > 40;
var gamma = alpha || beta;
Because the variable alpha contains a true Boolean value and beta contains a false one, the variable gamma is true because either one or the other has to be true, not both. Logical NOT (!)JavaScript's logical NOT (!) serves to negate an outcome. Sometimes, a built-in function has the opposite of what you might want to test in your script. The isFinite( ) function used in an example was negated to test for Infinity. The following script shows some different applications of the logical NOT: <html> <head> <title>Logical NOT</title> <script language="JavaScript"> var alpha = 200/0; var beta = !isFinite(alpha); var gamma = !(!alpha); var delta = !beta; var b="<br>"; combine = "alpha="+alpha+b+"beta="+beta+b+"gamma="+gamma+b+"delta="+delta; document.write(combine); </script> </head> <body bgcolor="mintcream"> </body> </html> The script generates the following output: alpha=Infinity beta=true gamma=true delta=false Because the alpha value generates Infinity, beta should generate true because the function !isFinite() tests for Infinity. However, the gamma variable also generates true. The negation of a variable containing a true Boolean literal generates false, but so will the negation of any other variable with a non-Boolean value. For example, these lines would return false: var alpha=5, beta=!alpha; document.write(beta); Because alpha does not contain a Boolean value, you might assume that alpha would be "neutral"-neither true or false. However, in the script where gamma returns true, a double NOT preceded it- !(!alpha). That is because !alpha would generate a Boolean false. Bitwise OperatorsIf your script calls for bitwise operations, you can use the symbols in table below to guide you. Generally, few programmers require bitwise operators, and they are only included here for a complete list of operators available in JavaScript and for programmers who may need them. NOTE Bitwise operations involve binary numbers, and you should understand how and when to effectively use binary numbers in a program. However, you can go through life as a very effective programmer, not to mention designer, and never have cause to use bitwise operators. However, if using bitwise operators is crucial to an envisioned JavaScript program that you have in mind, you will find that JavaScript provides an ample set of bitwise operators.
In certain respects, bitwise operators are like any others in the sense that you use them in the same kinds of expressions as any other operators in JavaScript. The key difference is that they work with binary (0s and 1s) instead of decimal values. To see what JavaScript is doing with bitwise operators, consider the first seven values in a binary number system: 0000 -0 0001 -1 0010 -2 0011 -3 0100 -4 0101 -5 0110 -6 If the digits in one were shifted to the left by one, the value 1 (0001) would become the value 2 (0010) because the digit in the fourth position from the right is moved to the third position and a 0 fills in where the 1 originally was. Hence, 0001 becomes 0010, or the decimal value 2. Using bitwise operators in JavaScript, you can complete the same kinds of operations. The following shows a single shift to the left, with decimal 3 becoming decimal 6: <html> <head> <title>Bitwise shift</title> <script language="JavaScript"> var alpha = 3 << 1; document.write(alpha); </script> </head> <body bgcolor="palevioletred"> </body> </html> The output to the screen is 6, but, for JavaScript, it simply shifts 0011 to 0110. Four bit operations are shown, but JavaScript converts the values to 32-bit integers internally so that all floating-point numbers are converted to integers and are rounded down (for example, 3.9999 becomes 3). Using typeofThe typeof operator is unary, returning one of the following values:
To use the operator, type the operator (typeof), a space and the operand, or place the operand in parentheses after the typeof operator. The following script shows the return of an array (object) and a Boolean value (boolean) using both methods of applying the operator: <html> <head> <title>typeof Operator</title> <script language="JavaScript"> var lots=new Array(); var whatTruth = 10 > 4; var kindOfData1= typeof lots; var kindOfData2 = typeof(whatTruth); var kindOfData=kindOfData1 + "<p>" + kindOfData2; document.write(kindOfData); </script> </head> <body bgcolor="wheat"> </body> </html> The new, delete, and void OperatorsOf these last three operators discussed, new is the most commonly used. All objects must begin with a constructor preceded by the new operator. As seen previously, the array object begins with the new operator: var family = new Array("Dad","Mom","Sue","Kris");
Likewise, other constructors for objects all use new. The delete operator removes an object property or array element in a script. For example, the following would undefine the array element with the string value Sue: var family = new Array("Dad","Mom","Sue","Kris");
delete family[2];
However, despite the operator's name, the element is not deleted; only the value is. The following script demonstrates what happens: <html>
<head>
<title>Delete Element Value</title>
<script language="JavaScript">
var family = new Array("Dad","Mom","Sue","Kris");
delete family[2];
document.write(family[3] + "<p>"+family.length);
</script>
</head>
<body bgcolor="peru">
</body>
</html>
The length of the array is still four, and the last element is still Kris. However, the third array element (element[2]), while no longer Sue, still exists. The delete operator simply undefined it. The final operator, void, is unary and operates on any literal or variable. Usually, you will see this operator as part of an <A> tag in an HTML script, such as here: <a href="javascript:void(0) "onClick="scroll(500,0)"> The void operator suppresses the display of values from evaluated expressions. All the viewer sees is javascript:void(0) in the window in the lower-left corner when the mouse moves over the link instead of the full expression, including the URL.
|
||||||||||||||||||||||
Disclaimer
1) E-articles is not responsible for the information contained by this article as well for any and all copyright infringements by authors and writers. E-articles is a free information resource. If you suspect this article for any copyright infringement, please read the terms of service and contact us to investigate the problem.
2) E-articles is not responsible for inaccuracies, falsehoods, or any other types of misinformation this article may contain and will not be liable for any loss or damage suffered by a user through the user's reliance on the information gained here. link to this article |