JavaScript Operators

JavaScript supports the following type of operators

  • Arithmetic Operators
  • Comparision Operators
  • Logical (or Relational) Operators
  • Assignment Operators
  • Conditional (Ternary Operators)
Arithmetic Operators

+ , - ,* , / , % , ++ , --


Example

<html>
<body>
<script type="text/javascript">
<!--
var a = 33; var b = 10;
var c = "Test";
var linebreak = "<br />"; 
document.write("a + b = ");
result = a + b; 
document.write(result);
 document.write(linebreak);
 document.write("a - b = "); 
 result = a - b; 
 document.write(result); 
 document.write(linebreak); 
 document.write("a / b = ");
 result = a / b;
 document.write(result); 
 document.write(linebreak); 
 document.write("a % b = ");
 result = a % b; 
 document.write(result);
 document.write(linebreak); 
 document.write("a + b + c = ");
 result = a + b + c;
 document.write(result); 
 document.write(linebreak);
 a = ++a;
 document.write("++a = ");
 result = ++a;
 document.write(result); 
 document.write(linebreak);
 b = --b;
document.write("--b = ");
 result = --b; 
 document.write(result);
 document.write(linebreak);
//-->
 </script>
Set the variables to different values and then try...
</body>
</html>


Using innerHTML

To access an HTML element, JavaScript can use the document.getElementById(id) method.

The id attribute defines the HTML element. The innerHTML property defines the HTML content:

Example

<html>
<body>
<p id="add"></p>
<script type="text/javascript">
document.getElementById("add").innerHTML=10+12;
 </script>
</body>
</html>



<html>
<body>
<button type="button" onclick="document.write(5 + 6)">Add the number</button>
</body>
</html>


<html>
<body>
<script>
window.alert(11 + 12);
</script>
</body>
</html>


Comparison Operators

==,!=,<,<=,>,>=

Logical Operators

JavaScript supports the following logical operators − &&,||,!

Bitwise Operators

& (Bitwise AND)

| (BitWise OR)

 ^ (Bitwise XOR)

 ~ (Bitwise Not)

 << (Left Shift)

>> (Right Shift)

This operator is just like the >> operator, except that the bits shifted in on the left are always zero.

Assignment Operators

= (Simple Assignment)

+= (Add and Assignment)

-= (Subtract and Assignment)

*= (Multiply and Assignment)

/= (Division and Assignment)

%= (Modules and Assignment)


Conditional Operator
The conditional operator first evaluates an expression for a true or false value and then executes one of the two given statements depending upon the result of the evaluation.


Example

<!DOCTYPE html>
<html>
<head>
<title>HTML Tutorials</title>
</head>
<body>
<p>Input your age and click the button:</p>
<input id="age" value="18" />
<button onclick="myFunction()">Check it</button>
<p id="eligble"></p>
<script>
function myFunction() {
  var age = document.getElementById("age").value;
  var voteable = (age < 18) ? "Too young":"Old enough";
  document.getElementById("eligble").innerHTML = voteable + " to vote.";
}
</script>
</body>
</html>

No comments:

Post a Comment