JavaScript Operator
Let us take a simple expression 4 + 5 is equal to 9. Here 4 and 5 are calledoperands and ‘+’ is called the operator. JavaScript supports the following types of operators.
- Arithmetic Operators
- Comparision Operators
- Logical (or Relational) Operators
- Assignment Operators
- Conditional (or ternary) Operators
Lets have a look on all operators one by one.
Arithmetic Operators
JavaScript supports the following arithmetic operators −
Assume variable A holds 10 and variable B holds 20, then −
Sr.No | Operator and Description |
---|---|
1 | + (Addition)
Adds two operands Ex: A + B will give 30 |
2 | – (Subtraction)
Subtracts the second operand from the first Ex: A – B will give -10 |
3 | * (Multiplication)
Multiply both operands Ex: A * B will give 200 |
4 | / (Division)
Divide the numerator by the denominator Ex: B / A will give 2 |
5 | % (Modulus)
Outputs the remainder of an integer division Ex: B % A will give 0 |
6 | ++ (Increment)
Increases an integer value by one Ex: A++ will give 11 |
7 | — (Decrement)
Decreases an integer value by one Ex: A– will give 9 |
Note − Addition operator (+) works for Numeric as well as Strings. e.g. “a” + 10 will give “a10”.
Example
The following code shows how to use arithmetic operators in JavaScript.
<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>
Output
a + b = 43 a - b = 23 a / b = 3.3 a % b = 3 a + b + c = 43Test ++a = 35 --b = 8 Set the variables to different values and then try...
Related Posts
- 72The 'for' loop is the most compact form of looping. It includes the following three important parts − The loop initialization where we initialize our counter to a starting value. The initialization statement is executed before the loop begins. The test statement which will test if a given condition is…
- 66
- 60
- 53Let us take a sample example to print out "Hello World". We added an optional HTML comment that surrounds our JavaScript code. This is to save our code from a browser that does not support JavaScript. The comment ends with a "//-->". Here "//" signifies a comment in JavaScript, so…
- 47