VirtualMV/JavaScript/Starting/Operators
Introduction
Overview
By the end of this page you will be able to:
|
Operators
Arithmetic operators
| Operator | Description | Example | Result |
| + | Addition | var intNum = 2+2; | 4 |
| - | Subtraction | var intNum = 5-2; | 3 |
| * | Multiplication | var intNum = 4*5; | 20 |
| / | Division | var intNum=15/5; var |
3 |
| % | Modulus (remainder after division) | var intNum = 5%2; var intNum = 10%8; |
1 2 |
| ++ | Increment | var intX=5; intX++; |
intX=6 |
| -- | Decrement | intX=3; intX--; |
intX=2 |
Comparison Operators
| Operator | Description | Example |
| == | is equal to | 4==8 returns false |
| != | is not equal | 4!=8 returns true |
| > | is greater than | 4>8 returns false |
| < | is less than | 4<8 returns true |
| >= | is greater than or equal to | 4>=8 returns false |
| <= | is less than or equal to | 4<=8 returns true |
Logical Operators
| Operator | Description | Example |
| && | and | x=5; |
| || | or | x=6; y=3; (x==5|| y==7) returns false |
| ! | not | x=6; y=4; x != y returns true; |
---
3 logicians walk into a cafe. The waiter asks "do you ALL want a drink?"
The first says "I don't know", the second says "I don't know" the third says "Yes please"
Conditional Operators
JavaScript also contains a conditional operator that assigns a value to a variable based on some condition. JavaScript Comparison and Logical Operators (W3Schools)
Examples
The following code shows that JavaScript allows for some quite sophisticated assignments.
//This allows you to change a greeting based on the contents of the txtVisitor variable //if the visitor = PRES then put Dear President otherwise just Dear var txtGreeting=(txtVisitor=="PRES")?"Dear President ":"Dear "; // Here a date object is created. // If d is < 10 then a zero is added to the front else just leave d as is. var date = new Date(); var d = date.getDate(); var day = (parseInt(d) < 10) ? '0' + d : d;
Example (js1_05)
<html> <body> <script type="text/javascript"> var intA = 3; var intB = 5; var intSum = intA + intB; var intProd = intA * intB; document.write("The sum of 3 and 5 is " + intSum +"<br />"); document.write("The product of 3 and 5 is " + intProd); </script> <p>This example declares some variables, assigns values to them, performs a calculation and then displays the results.</p> </body> </html>
Example :Click here to run js1_05.
Note that in the example the variables are assigned numbers. If you accept values from a prompt or a text box (from a form) the "numbers" are actually text so need to be converted if you want to do arithmetic operations on them.
References
|
virtualMV | Superquick wiki guide | Please give me some feedback |
VirtualMV/JavaScript/Starting/Operators. (2026). In WikiEducator/VirtualMV wiki. Retrieved June 18, 2026, from http:https://wikieducator.org/VirtualMV/JavaScript/Starting/Operators (zotero)
|