﻿ JavaScript tutorial-operators

JavaScript tutorial-operators

JavaScript operators

JavaScript has many different operators such as assignment, comparison, arithmetic and logical operators.

-Assignment operators

The basic assignment operator is = sign. It is used to assign the value of the right operant to the left operand. The table below shows the uses of assignment operator in basic math calculation.
 Operator Meaning x += y x = x + y x -= y x = x - y x *= y x = x * y x /= y x = x / y

Example:

<HTML>
<SCRIPT>
<!--
var a;
var b;
function  Divide(){
a=10;

b=20;

c=b/a;
return(c);

}

document.write(“ b divided by a = ” +Divide()); -->
</SCRIPT>
<BODY bgcolor=”blue”>
</BODY>
</HTML>

-Comparison operators

A comparison operator is used to compare its operands and return logical value such as true or false. When used on string values, the comparisons are based on the standard lexicographical ordering. They are described in the following table.

 Operator Description Example Equal (= =) Returns true if the operands are equal. x == y returns true if x equals y. Not equal (!=) Returns true if the operands are not equal. x != y returns true if x is not equal to y. Greater than (>) Returns true if left operand is greater than right operand. x > y returns to true if x is greater than y. Greater than or equal (>=) Returns true if left operand is greater than or equal to right operand. x >= y returns to true if x is greater than or equal to y. Less than (<) Returns true if left operand is less than right operand. x < y returns to true if x is less than y. Less than or equal (<=) Returns true if left operand is less than or equal to right operand. x <= y returns true if x is less than or equal to y.

Example:

<HTML>
<SCRIPT>
<!--
var a;

var b;

function  checkEqual(){

a=10;

b=20;

if (a==b) return true;

else return false;

}
document.write(“checkEqual returns ” +checkEqual());
-->
</SCRIPT>
<BODY bgcolor=”yellow”>
</BODY>
</HTML>

-Arithmetic Operators

The standard arithmetic operators are addition (+), subtraction (-), multiplication (*), division (/) and remainder (%). These operators are used for basic calculation such as addition, subtraction, multiplication, division, and remainder of division. Note: To add 1 to a numerical variable, you can write nameOfvariable++. To subtract 1 from the variable, you can write nameOfvariable--.

-Logical Operators

Logical operators take Boolean (logical) values as operands and return a Boolean value (true or false). Consider the following table:

 Operator Sign Usage Description and && a && b True if both logical expressions a and b are true. False otherwise. or || a || b True if either logical expression a or b is true. False if both a and b are false. not ! !a False if a is true; true if a is false.

Example:

<HTML>
<SCRIPT>
<!--
var a;
var b;
function  bothTrue(){
a=true;

b=true;
if (a && b) return true;

else return false;
}
document.write(“a and b are  ” +bothTrue());
-->
</SCRIPT>