operators and expressions operators are symbols that produce a result based on some rules. examples:...

38
Operators and Expressions Operators are symbols that produce a result based on some rules. Examples: +, -, =, > and <. An operator manipulates data objects called operands. Binary operators manipulates two operands. Operands can be strings, numbers or Booleans.

Upload: juliet-lorrain

Post on 14-Dec-2015

221 views

Category:

Documents


0 download

TRANSCRIPT

Operators and Expressions

Operators are symbols that produce a result based on some rules.

Examples: +, -, =, > and <.

An operator manipulates data objects called operands. Binary operators manipulates two operands.

Operands can be strings, numbers or Booleans.

Assignment Operator

• The 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.

Ex: var result = 1 + 2;

Precedence and AssociativityOperator Description Associativity

() parentheses Left to Right

++; -- auto increment; decrement Right to Left

! logical NOT Right to Left

*; /; % multiply;divide;modulus Left to Right

+; - add;subtract Left to Right

+ concatenation Left to Right

<; <= Less-than; Less-than-equal-to

Left to Right

>; >= Greater-than; Greater-than-equal-to

Left to Right

==; != equal-to; not equal-to Left to Right

===; !== identical to; not identical to Left to Right

& bitwise AND Left to Right

Operator Description Assoc.

| bitwise OR Left to Right

^ bitwise XOR Left to Right

~ bitwise NOT Left to Right

<< bitwise left shift Left to Right

>> bitwise right shift Left to Right

>>> bit zero-filled,right shift Left to Right

&& logical AND Left to Right

|| logical OR Left to Right

?: ternary conditional Right to Left

=; +=; -=; *=; /=; %=; assignment Right to Left

, (comma)

Example<html>

<head>

<title>First JavaScript Sample</title>

<script language = "JavaScript">

var result = 5 + 4 * 12 / 4;

document.write(“result = ” + result + "<br>");

</script>

</head>

<body bgcolor="yellow" text="blue">

</body>

</html>

Example 2<html>

<head><title>Precedence and Associativity</title></head>

<body><script language = "JavaScript"> var x = 5 + 4 * 12 / 4; document.write( "<h3>The result is " + x + "<br>"); var x = ( 5 + 4 ) * ( 12 / 4 ); document.write("The result is " + x + "<br>");</script></body>

</html>

Arithmetic Operators

Operators/Operands Function

x+y addition

x-y subtraction

x*y multiplication

x/y division (returns floating-point number)

x%y modulus

Example 3<html>

<head><title>Arithmetic Operators</title></head>

<body><h2>Arithmetic operators</h2><p><script language="JavaScript"> var num1 = 5; var num2 = 7; var result = num1 + num2; document.write("<h3>num1 + num2 = "+ result</h3>); result = result + (10 / 2 + 5); document.write("<h3>12 + (10 / 2 + 5) = " + result</h3>);</script></body>

</html>

Shortcut Assignment Operators

Operator Example Meaning

= var x=1; assign 1 to variable “x”

+= x+=2; add 2 to “x” and assign result to “x”

-= x-=3; subtract 3 from “x” and assign result to “x”

*= x*=4; multiply x by 4 and assign result to “x”

/= x/=5; divide x by 5 and assign result to “x”

%= x%=6; divide x by 6 and assign remainder to “x”

Example 4<html>

<head><title>Assignment and Shortcut Operators</title><script language = "JavaScript"> var num=10; document.write("<br>" + "num is assigned " + 10); num += 2; document.write("<br>num += 2; num is " + num ); num -= 1; document.write("<br>num -= 1; num is " + num); num *= 3; document.write("<br>num *= 3; num is " + num); num %= 5; document.write("<br>num %= 5; num is " + num);</script></head>

<body bgcolor="yellow" text="blue"></body>

</html>

Autoincrement and Autodecrement Operators

(++) – increment the value of its operand by 1

(--) – decrement the value of its operand by 1

Prefixes: ++x; --x

Postfixes: x++; x--

When used with assignment, they are different.

y=0; x=5;

y=++x; => y = 6 and x = 6

y=x++; => y = 5 and x = 6

Example 5<html>

<head><title>Auto-increment and Auto-decrement</title></head>

<body> <script language = "JavaScript"> var x=5; var y=0; y = ++x; // add one to x first; then assign to y document.write("<h3>Pre-increment:<br>"); document.write("y is " + y + "<br>"); document.write("x is " + x + "<br>"); document.write("-----------------------<br>"); var x=5; var y=0; y=x++; // assign value in x to y; then add one to x document.write("<h3>Post-increment:<br>"); document.write("y is " + y + "<br>"); document.write("x is " + x + "<br></h3>"); </script></body>

</html>

Concatenation Operator

• (+) – is used as concatenation operator. It is the only operator to manipulate strings.

• If the operands are a mix of strings and numbers, JavaScript will convert the numbers to string.

• (+=) – concatenates two strings and assigns the result to x, like:

• x=“hot”; x +=“dog”; x now is “hotdog”.

Comparison OperatorsOperator/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 or equal than y

x<y x is less than y

x<=y x is less or equal than y

x===y x is identical to y in value and type

x!==y x is not identical to y

Equal and Identical• Two strings are equal if they have the same

length and same characters in corresponding position. Two numbers are equal if they have the same numeric value.

• Identical are not only the same value, but also of the same data type:

“54”== 54 => true

“54”===54 => false

true==1 => true

true===1 => false

Example 6<html>

<head><title>Comparing Numbers</title></head>

<body> <script language = "JavaScript"> var x = 5;

var y = 4;var result = x > y;document.writeln("<h3>The result is "+ result + ".<br>");result = x < y;document.writeln( "The result is " + result + ".<br>");

</script></body>

</html>

Comparing strings - Example 7<html>

<head><title>Comparing Strings</title></head>

<body> <script language = "JavaScript">

var fruit1 = "pear";var fruit2 = "peaR";var result = fruit1 > fruit2;document.writeln( "<h3>The result is "+ result + ".<br>");result = fruit1 < fruit2;document.writeln( "The result is " + result + ".<br>");result = fruit1 === fruit2;// Are they identical; i.e., value and type are the same?document.writeln( "The result is " + result + ".<br>");

</script></body>

</html>

Logical Operators• Most often used in “if” statements.• Numeric operand is true if it evaluates to any

number that is not zero.

Operator/Operands Function

num1 && num2 true if num1 is true and num2 is true

num1 || num2 true if num1 is true or num2 is true

! num1 Not num1: true if num1 is false

Logical AND

• Whatever is suppose to happen is based on two conditions, and both conditions must be met.

• If the left hand expression of the AND operator is evaluate to zero, the expression is false and the right hand expression is not evaluated.

Example 8<html>

<head><title>Logical AND Operator</title></head>

<body bgcolor="lightblue"><script language="JavaScript"> var answer = prompt("How old are you? ", ""); if ( answer > 12 && answer < 20 ) { alert("Teenagers rock!"); }</script></body>

</html>

Logical OR

• Whatever is suppose to happen is based in two conditions, and only one condition must be met.

• If the expression on the left hand side of the OR operator is evaluated to true, the value of the expression is true and the right hand side expression is not evaluated.

Example 9<html>

<head><title>Logical OR Operator</title></head>

<body bgcolor="lightblue"><script language="JavaScript"> var answer = prompt("Where should we eat? ", ""); if ( answer == "McDonald's" || answer == "Taco Bell" || answer == "Wendy's"){ alert("No fast food today, thanks."); }</script></body>

</html>

Logical NOT

• It is used for a negation.

• The ! is called an unary operator because it has only one operand.

• !null => true

• !undefined => true

Example 10<html>

<head>

<title>Logical NOT Operator</title>

</head>

<body bgcolor="lightblue">

<script language="JavaScript">

var answer = true;

alert("Was ” + answer + “. Now " + !answer);

</script>

</body>

</html>

Example 11<html>

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

<body></body>

</html>

Conditional Operator• It is called a ternary operator because it

requires three operands.

• It is a short hand of the if/else conditional statement.

• 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;

Example 12<html>

<head><title>Conditional Operator</title></head>

<body bgcolor="lightblue"><script language="JavaScript"> var age = prompt("How old are you? ", ""); var price = (age > 55 ) ? 0 : 7.50; alert("You pay $" + price + 0);</script></body>

</html>

Bitwise Operator• Treat their operands as a set of 32 bits.

Operator Function

& Bitwise AND

| Bitwise OR

^ Bitwise XOR

~ Bitwise NOT

<< Left shift

>> Right shift

>>> Zero-fill right shift

Example 13<html>

<head><title>Bitwise Operators</title></head>

<body bgcolor="lightblue"><font size="+1" face="arial"><h3> Testing Bitwise Operators</h3><script language="JavaScript">

var result = 15 & 9;document.write("15 & 9 yields: " + result);result = 15 | 9;document.write("<br> 15 | 9 yields: " + result);result = 15 ^ 9;document.write("<br> 15 ^ 9 yields: " + result);result = 9 << 2;document.write("<br> 9 << 2 yields: " + result);result = 9 >> 2;document.write( "<br> 9 >> 2 yields: " + result);result = -9 >> 2;document.write( "<br> -9 >> 2 yields: " + result);result = 15 >>> 2;document.write( "<br> 15 >>> 2 yields: " + result);

</script></body>

</html>

Datatype Conversion

• JavaScript is a loosely typed language. It automatically converts values when it assigns values to a variable or evaluates an expression.

• Sometimes you need to force conversions.

• JavaScript provides String(), Number() and Boolean() Methods.

Example 14<html>

<head><title>The Conversion Methods</title></head>

<body><p><h3>Data Conversion</h3><script language="JavaScript">

var num1 = prompt("Enter a number: ","");var num2 = prompt("Enter another number: ","");var result = Number(num1) + Number(num2); // Convert strings to numbersalert("Result is "+ result);var myString=String(num1);result=myString + 200; // String + Number is Stringalert("Result is "+ result); // Concatenates 200 to the result; alert("Boolean result is "+ Boolean(num2)); // Prints true

</script></body>

</html>

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.

• In the two-argument format, the first argument is the string to be parsed and the second argument is the number base of the number.

Example 15<html>

<head><title>Using the parseInt() Function</title></head>

<body><b><script language = "JavaScript"> var grade = prompt("What is your grade? ", ""); // grade entered as a string grade=parseInt(grade); // grade converted to an integer document.write("grade type is<em> " + typeof(grade)); grade+=10; document.write("<em><br>After a 10 point bonus, your grade is “ + grade

+ "!<br>");</script></body>

</html>

The parseFloat() Method

• It is exactly like the pasrseInt() Method, except that it returns a floating point number.

Example 16<html>

<head><title>Using the parseFloat() Function</title><script language = "JavaScript">

var temp = prompt("What is your temperature? ", "");temp=parseFloat(temp);if(temp == 98.6){ alert("Your temp is normal");}else{ alert("You are sick!");}

</script></head>

<body></body>

</html>

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.

Example 17<html>

<head><title>The eval() Function</title></head>

<body bgcolor="lightblue"><script language="JavaScript">

var str="5 + 4";var num1 = eval(str);var num2 = eval(prompt("Give me a number ", ""));alert(num1 + num2);

</script></body>

</html>

Special Operators

Will be discussed later in the course.Some examples:• , (comma)• delete• function• instanceof• new• this• void