0% found this document useful (0 votes)
17 views

Javascript Operators

Uploaded by

raizakaecy
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
17 views

Javascript Operators

Uploaded by

raizakaecy
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 13

About JavaScript Operators and Expressions

Data objects can be manipulated in a number of ways by the large number of operators provided by JavaScript.
Operators are symbols, such as +, –, =, >, and <, that produce a result based on some rules. An operator manipulates
data objects called operands; for example, 5 and 4 are operands in the expression 5 + 4. Operators and operands are
found in expressions. An expression combines a group of values to make a new value, n = 5 + 4. And when you
terminate an expression with a semicolon, you have a complete statement (e.g., n = 5 + 4;).

Assignment

An assignment statement evaluates the expression on the right-hand side of the equal sign and assigns the result to
the variable on the left-hand side of the equal sign. The equal sign is the assignment operator.

var total = 5 + 4;
var friend = "Tony";

Precedence and Associativity

When an expression contains a number of operators and operands, such as 5 * 4 + 3 / –2.2, and the order of
evaluation is ambiguous, then JavaScript must determine what to do. This is where the precedence and associative
rules come in. They tell JavaScript how to evaluate such an expression. Precedence refers to the way in which the
operator binds to its operand, such as, should addition be done before division or should assignment come before
multplication? The precedence of one operator over another determines what operation is done first. In the rules of
precedence, the multiplication operator is of higher precedence than the addition operator, technically meaning the
operator of higher precedence binds more tightly to its operands. The assignment operators are low in precedence
and thus bind loosely to their operand. In the expression sum = 5 + 4 the equal sign is of low precedence, so the
expression 5 + 4 is evaluated first and then the result is assigned to sum. Parentheses are of the highest precedence.
An expression placed within parentheses is evaluated first; thus, in the expression 2 * (10 – 4), the expression within
the parentheses is evaluated first and that result is multiplied by 2. When parentheses are nested, the expression
contained within the innermost set of parentheses is evaluated first.

Associativity refers to the order in which an operator evaluates its operands: left to right in no specified order, or
right to left. When all of the operators in an expression are of equal precedence, normally the association is left to
right; in the expression 5 + 4 + 3, the evaluation is from left to right.

Example:

<html>
<head>
<title>Precedence and Associativity</title>
</head>
<body>
<script language = "JavaScript">
1 var x = 5 + 4 * 12 / 4;
2 document.writeln( "<h3>The result is " + x + "<br>");
3 var x = ( 5 + 4 ) * ( 12 / 4 );
4 document.writeln("The result is " + x);
</script>
</body>
</html>

EXPLANATION

1. The variable, called x, is assigned the result of the expression.


2.
3. var x = 5 + 4 * 12 / 4;

results in

x = 5 + 48 / 4

results in

x = 5 + 12

results in

17

Since multiplication and division are higher on the precedence table than addition, those expressions will
be evaluated first, associating from left to right.

4. The result of the previous evaluation, the value of x, is sent to the browser.
5. The expressions enclosed in parentheses are evaluated first and then multiplied.
6.
7. var x = ( 5 + 4 ) * ( 12 / 4 );

results in

x = 9 * 3

results in

27

8. The result of the previous evaluation, the value of x, is sent to the browser. The output of the script is
shown in Figure 5.2.

4Figure 5.2. Output from Example 5.2.


Types of Operators

Arithmetic Operators

Arithmetic operators take numerical values (either literals or variables) as their operands and return a single
numerical value. The standard arithmetic operators are addition (+), subtraction (–), multiplication (*), and
division (/).

Shortcut Assignment Operators

The shortcut assignment operators allow you to perform an arithmetic or string operation by combining an
assignment operator with an arithmetic or string operator. For example, x = x + 1 can be written x+=1.

Autoincrement and Autodecrement Operators

To make programs easier to read, to simplify typing, and, at the machine level, to produce more efficient code, the
autoincrement (++) and autodecrement (– –) operators are provided.

The autoincrement operator performs the simple task of incrementing the value of its operand by 1, and the
autodecrement operator decrements the value of its operand by 1. The operator has two forms: the first form prefixes
the variable with either ++ or – – (e.g., ++x or – –x); the second form postfixes (places the operator after) the
variable name with either ++ or – – (e.g., x++ or x– –). For simple operations, such as x++ or x– –, ++x or – –x, the
effect is the same; both ++x and x++ add one to the value of x, and both – –x and x– – subtract one from the value of
x.

Now you have four ways to add 1 to the value of a variable:

x = x + 1;
x += ;
x++;
++x;

and four ways to subtract 1 from the value of a variable:

x = x – 1;
x –= 1;
x– –;
– –x;

Concatenation Operator
As shown in previous examples, the + sign is used for concatenation and addition. The concatenation operator, the +
sign, is a string operator used to join together one or more strings. In fact, the concatenation operator is the only
operator JavaScript provides to manipulate strings.

Comparison Operators

When operands are compared, relational and equality operators are used. The operands can be numbers or strings.
The result of the comparison is either true or false—a Boolean value.

Table 5.6. Comparison operators.


Operator/Operands Function
x == y x is equal to y
x != y x is not equal to y
x>y x is greater than y
x >= y x is greater than or equal to y
x<y x is less than y
x <= y x is less than or equal to y
x===y x is identical to y in value and type
x != = y x is not identical to y

Logical Operators

The logical operators allow you combine the relational operators into more powerful expressions for testing
conditions and are most often used in if statements. They evaluate their operands from left to right, testing the
Boolean value of each operand in turn: Does the operand evaluate to true or false? In the expression if ( x > 5 && x
< 10 ), the && is a logical operator. The expression simplified means, "if x is greater than 5 and x is also less than
10, then do something"; in the case of the logical AND (&&), if the first expression returns true and the second
expression also returns true, then the whole expression is true. If instead of && we used ||, the operator means OR
and only one of the expressions must be true.

The three logical operators are the logical AND, logical OR, and logical NOT. The symbol for AND is &&, the
symbol for OR is ||, and the symbol for NOT is !.

The && Operator (Logical AND)

We all know the meaning of the English statement, "If you have the money and I have the time...." Whatever is
supposed to happen is based on two conditions, and both conditions must be met. You must have the money and I
must have the time. JavaScript uses the symbol && to represent the word AND. This operator is called the logical
AND operator. If the expression on the left-hand side of the && evaluates to zero, null, or the empty string "", the
expression is false. If the expression on the left-hand side of the operator evaluates to true (non-zero), then the right-
hand side is evaluated, and if that expression is also true, then the whole expression is true. If the left-hand side
evaluates to true, and the right-hand side is false, the expression is false. If evaluated as Booleans, the same rules
apply, except the returned value will be either Boolean true or false.

Example:

<html>
<head><title>Logical AND Operator</title>
</head>
<body bgcolor="lightblue">
<font="+1">
<script language="JavaScript">
1 var answer = prompt("How old are you? ", "");
2 if ( answer > 12 && answer < 20 ) {
alert("Teenagers rock!");
}
</script>
</body>
</html>

The || Operator (Logical OR)

In the English statement "If you have some cash or I have a credit card..." the word or is used in the condition. With
the or, only one of the conditions must be met (hopefully that you have the cash!). JavaScript uses the || symbol to
represent the logical OR. If the expression on the left-hand side of the || operator is evaluated as true (non-zero), the
value of the expression is true, and no further checking is done. If the value on the left-hand side of the || operator is
false, the value of the expression on the right-hand side of the operator is evaluated, and if true, the expression is
true; that is, only one expression must be true. Once an expression returns true, the remaining expressions can be
either true or false. It doesn't matter, as long as one expression is true.

Example:

<html>
<head>
<title>Logical OR Operator</title>
</head>
<body bgcolor="lightblue">
<font="+1">
<script language="JavaScript">

1 var answer = prompt("Where should we eat? ", "");


2 if ( answer == "McDonald's" || answer == "Taco Bell" ||
answer == "Wendy's"){
3 alert("No fast food today, thanks.");
}
</script>
</body>
</html>

EXPLANATION

1. The user is prompted to choose a place to eat. The variable called answer is assigned the value he enters.
(See Figure 5.13.)

Figure 5.13. The user enters a value.

2. If the value of answer is any one of McDonald's or Taco Bell or Wendy's, the statement enclosed within the
curly braces, is executed: an alert box appears displaying No fast food today, thanks. (See Figure 5.14.) If
he enters any other value, nothing happens.

Figure 5.14. If the user enters any one of the values in line 2, this alert box appears.
The ! Operator (Logical NOT)

In the English statement "That's not true!" the word not is used for negation: not true is false, and not false is true.
JavaScript provides the NOT (!) operator for negation. The ! operator is called a unary operator because it has only
one operand; for example, ! true or ! 5. It returns true if the expression evaluates to false and returns false if the
expression evaluates to true

Example 5:

<html>
<head>
<title>Logical NOT Operator</title>
</head>
<body bgcolor="lightblue">
<font="+1">
<script language="JavaScript">
1 var answer = true;
2 alert("Was true. Now " + ! true);
</script>
</body>
</html>

EXPLANATION

1. The Boolean value true is assigned to the variable answer.


2. The expression sent to the alert dialog box, ! true, negates the value true, (not true) making it false. (See
Figure 5.15.)

Figure 5.15. The ! operator caused true to become false.

In summary, the following example illustrates the logical operators and the values they return.

Example 5.11

<html>
<head>
<title>Logical (Boolean) Operators</title>
</head>
<body>
<script language = "JavaScript">
1 var num1=50;
var num2=100;
var num3=0;
2 document.write("<h3>num1 && num2 is " + (num1 && num2) +
".<br>");
3 document.write("num1 || $num2 is " + (num1 || num2) +".<br>");
4 document.write("! num1 is " + !num1 +".<br>");
5 document.write("!(num1 && num2) is " + !(num1 && num2) +
".<br>");
6 document.write("!(num1 && num3) is " + !(num1 && num3) +
".<br>");
</script>
</body>
</html>

EXPLANATION

1. Three variables, num1, num2, and num3, are initialized.


2. The && operator expects both of its operands to be true, if the expression is to be true. A true value is any
number that is not zero. In the expression, 50 && 100, both operands are true. The value of the last true
operand, 100, is returned.
3. The || operator expects only one of its operands to be true if the whole expression is to be true. 50 || 100 is
true because the first operand evaluates to a non-zero value. Because 50 is true and only one operand must
be true, the evaluation stops here and 50 is returned.
4. The ! (NOT) operator negates its operand. ! 50 means ! true; that is, false.
5. Because the expression num1 && num2 is enclosed in parentheses, it is evaluated first, resulting in 50 &&
100, true. Then the ! (NOT) operator evaluates ! (true), resulting in Boolean false.
6. The expression, num1 && num3, enclosed in parentheses, is evaluated first. Since num3 is 0, the
expression evaluates to false. ! (false) is true. See Figure 5.16.

Figure 5.16. Output from Example 5.11.

The Conditional Operator

The conditional operator is called a ternary operator because it requires three operands. It is often used as a
shorthand method for if/else conditional statements. (See Chapter 6, "Under Certain Conditions.") Although we
cover if/else in Chapter 6, the format below shows both the conditional operator and how it translates to an if/else
statement.

FORMAT

conditional expression ? expression : expression

Examples:

x ? y : z If x evaluates to true, the value of the expression


becomes y, else the value of the expression becomes z

big = (x > y) ? x : y If x is greater than y, x is assigned to


variable big, else y is assigned to
variable big
The same conditional operator as an if/else statement:

if (x > y) {
big = x;
}
else{
big = y;
}

Example:

<html>
<head>
<title>Conditional Operator</title>
</head>
<body bgcolor="lightblue">
<font="+1">
<script language="JavaScript">
1 var age = prompt("How old are you? ", "");
2 var price = (age > 55 ) ? 0 : 7.50;
3 alert("You pay $" + price + 0);
</script>
</body>
</html>

EXPLANATION

1. The user is prompted for input. The value he enters in the prompt box is assigned to the variable age. (See
Figure 5.17.)

Figure 5.17. The user enters 12. This value is assigned to variable age in the program.

2. If the value of age is greater than 55, the value to the right of the ? is assigned to the variable price; if not,
the value after the : is assigned to the variable price.
3. The alert dialog box displays the value of the variable price. (See Figure 5.18.)

Figure 5.18. Since the age is not greater than 55, the price is assigned 7.50. (IE displays $7.50.)

Number, String, or Boolean? Datatype Conversion

As defined earlier, JavaScript is a loosely typed language, which really means that you don't have to be concerned
about what kind of data is stored in a variable. You can assign a number to x on one line and on the next line assign
a string to x, you can compare numbers and strings, strings and Booleans, and so on. JavaScript automatically
converts values when it assigns values to a variable or evaluates an expression. If data types are mixed (i.e., a
number is compared with a string, a Boolean is compared with a number, a string is compared with a Boolean),
JavaScript must decide how to handle the expression. Most of the time, letting JavaScript handle the data works fine,
but there are times when you want to force a conversion of one type to another. For example, if you prompt a user
for input, the input is set as a string. But, suppose you want to perform calculations on the incoming data, making it
necessary to convert the strings to numbers. When using the + operator you want to add two numbers that have been
entered as strings, not concatenate them, so you will then need to convert the data from string to number.

JavaScript provides three methods to convert the primitive data types. They are:

String()
Number()
Boolean()

Example:

<html>
<head><title>The Conversion Methods</title></head>
<body>
<p>
<h3>Data Conversion</h3>
script language="JavaScript">
1 var num1 = prompt("Enter a number: ","");
var num2 = prompt("Enter another number: ","");
2 var result = Number(num1) + Number(num2);
// Convert strings to numbers
3 alert("Result is "+ result);
4 var myString=String(num1);
5 result=myString + 200; // String + Number is String
6 alert("Result is "+ result); // Concatenates 200 to the
// result; displays 20200
7 alert("Boolean result is "+ Boolean(num2)); // Prints true
</script>
</body>
</html>

EXPLANATION

1. The user is prompted to enter a number (see Figure 5.20). The variable num1 is assigned the number. On
the next line, num2 is assigned another number entered by the user (see Figure 5.21).

Figure 5.20. The user is prompted to enter a number.

Figure 5.21. The user is prompted to enter another number.


2. The JavaScript Number() method converts strings to numbers. After the variables, num1 and num2 have
been converted to numbers, the + sign will be used as an addition operator (rather than a concatenation
operator), resulting in the sum of num1 and num2. Unless converted to numbers, the string values 30 + 20
would be concatenated, resulting in 3020.
3. The alert() box displays the sum of the two numbers entered by the user (see Figure 5.22).

Figure 5.22. The result is displayed.

4. The variable num1 is converted to a string; its value is assigned to the variable, result.
5. The value of myString, 20, is concatenated to 200 and assigned to result. The result is 20200.
6. The alert() box displays the result from line 5.
7. The value of num2 is converted to Boolean, either true or false. Since the value of num2 is not 0, true is
displayed in the alert() dialog box.

The parseInt() Method

This method converts a string to a number. It starts parsing at the beginning of the string and returns all integers
until it reaches a non-integer and then stops parsing. If the string doesn't begin with an integer, NaN[2] (not a
number) is returned. For example, parseInt("150cats") becomes 150, whereas parseInt("cats") becomes NaN.

Example:

<html>
<head>
<title>Using the parseInt() Function</title></head>
<body><font face="arial size="+1">
<b>
<script language = "JavaScript">
1 var grade = prompt("What is your grade? ", "");
// Grade entered as a string
2 grade=parseInt(grade); // Grade converted to an integer
3 document.write("grade type is<em> " + typeof(grade));
4 grade+=10;
5 document.write("<em><br>After a 10 point bonus, your grade is "
+ grade + "!<br>");
</script>
</body>
</html>

EXPLANATION

1. The user is prompted to enter a grade. The string value entered in the prompt box is assigned to the variable
grade. (See Figure 5.23.)

Figure 5.23. The user enters a grade.


2. The parseInt() method will convert the grade to an integer value.
3. The typeof() operator returns the data type of the variable grade.
4. The value of grade is incremented by 10.
5. The new value of grade is sent to the browser. (See Figure 5.24.)

Figure 5.24. The new value of grade is displayed in the browser.

5.3.2 The parseFloat() Method

The parseFloat() method is just like the parseInt() method except that it returns a floating-point number. A floating-
point[3] number is a number that contains a fractional part, such as 3.0, –22.5, or .15. The decimal point is allowed in
the string being parsed. If the string being parsed does not start with a number, NaN (not a number) is returned.

[3]
The term "floating point" means that there are not a fixed number of digits before or after the decimal point; the
decimal point floats.

FORMAT

parseFloat(String);

Example:

parseFloat("45.3 degrees");
Table 5.16. parseFloat(String).
String Result
"hello" NaN
"Route 66.6" NaN
"6.5 dogs" 6.5
"6" 6
"6.56" 6.56

Example 5.16

<html>
<head>
<title>Using the parseFloat() Function</title>
<script language = "JavaScript">
1 var temp = prompt("What is your temperature? ", "");
2 temp=parseFloat(temp);
3 if(temp == 98.6){
4 alert("Your temp is normal");
}
5 else{
alert("You are sick!");
}
</script></head><body></body></html>
EXPLANATION

1. The user is prompted for input and the result is assigned as a string to the variable temp. (See Figure 5.25.)

Figure 5.25. User enters a string. The parseFloat() method will convert it to a floating-point number.

2. The parseFloat() method converts the string into a floating-point number and assigns it to temp.
3. Although we haven't formally covered if statements, this example should be easy to follow. If the value of
temp is equal to 98.6, then the following block of statements will be executed.
4. If is the user entered 98.6, the alert box sends the message "Your temp is normal" to the browser.
5. If line 3 is not true, the block of statements following else is executed. An alert box will appear in the
browser window saying, "You are sick!". (See Figure 5.26.)

Figure 5.26. Output from Example 5.16.

The eval() Method

The eval() method evaluates a string of JavaScript statements and evaluates the whole thing as a little program,
returning the result of the execution.[4] If there is no result, undefined is returned.

[4]
The eval() method takes a primitive string as its argument, not a String object. If a String object is used, it will be
returned as is.

FORMAT

eval(String);

Example:

eval("(5+4) / 3");

Example 5.17

<html>
<head>
<title>The eval() Function</title>
</head>
<body bgcolor="lightblue">
<font size="+1" face="arial">
<script language="JavaScript">
1 var str="5 + 4";
2 var num1 = eval(str);
3 var num2 = eval(prompt("Give me a number ", ""));
4 alert(num1 + num2);
</script>
</body>
</html>

EXPLANATION

1. The string "5 + 4" is assigned to the variable str.


2. The eval() method evaluates the string expression "5 + 4" as a JavaScript instruction. The variable num1 is
assigned 9, the sum of 5 + 4.
3. The eval() method evaluates the string value that is entered into the prompt dialog box. (See Figure 5.27.)
The prompt() method always returns a string value. If the value in the string is a number, eval() will convert
the string to a number, return the number, and assign it to num2.

Figure 5.27. The eval() method converts the user input, a string, to a number.

4. The alert() method displays the sum of num1 and num2 in the browser window. (See Figure 5.28.)

Figure 5.28. Output from Example 5.17.

You might also like