Now we will learn in JavaScript Tutorial that Operators in JavaScript allow us to control our values, such as multiplying two numbers, adding two strings together
and much more....
JavaScript has a full range of operators, including arithmetic operators, logical
operators, bitwise JavaScript Operators, and assignment operators. There are also a few
diverse operators in JavaScript that will be explain under here.
JavaScript Operator |
Description of JavaScript Operator |
Examples of JavaScript Operator |
+ (add) |
Adds numeric operands or concatenates
two or more strings in JavaScript. |
1) v+y 2) "Me"+" You"
Result: "Me You" |
- (subtract) |
Subtracts numeric operands in
JavaScript. |
x-7 |
* (multiply) |
Multiplies numeric operands in
JavaScript. |
5*2 |
/ (divide) |
Divides numeric operands. |
y/v |
% (modulo) |
Returns the remainder when the first
operand is divided by the second operand. |
7%2
Result: 1 |
++ (increment) |
Increments the operand by one. Note the
following two possible behaviors in JavaScript increment operator 1) If operator is used before
operand like (++v), then it increments the operand and evaluates to the
incremented value.
2) If operator is used following operand like (v++), it increments
the operand but evaluates to the un incremented value. |
Using v=2 for each example below: 1)
v++
Result: v=3
2) y= ++v
Result: 3
3) y= v++
Result: y=2 |
-- decrement |
Decrements the operand by 1. Note the
following two possible behaviors: 1) If operator is used before
operand like (--v), it increments the operand and evaluates to the
incremented value.
2) If operator is used following operand like (v--), it increments
the operand but evaluates to the un incremented value. |
v-- |
Tip: With all of the JavaScript Operators above except Addition +, if an operand used is non numeric, operator will attempt to convert it to a number first.
This example uses the Bitwise Operator Shift Left to shift the
value 2 to the left four bits (binary 10 to binary 1000), resulting in 8:
var test=2;
test=test<<2
alert(test) //alerts 8
The Conditional Operator is extremely handy for quickly
assigning a different value to a variable depending on the outcome of an
evaluation. Here are two examples:
var browser=(navigator.appName.indexOf("Microsoft")!=-1)?
"IE" : "Non IE"
You can expand the number of possible values to assign to more than just two.
In fact, there is no limit. Observe the below example, which has 3 possible
values:
var browser=(navigator.appName.indexOf("Microsoft")!=-1)?
"IE" : (navigator.appName.indexOf("Netscape")? "NS" : "Not IE nor NS"
In the
2nd example here in JavaScript Tutorial, "browser" will contain one of 3 possible values depending on the
browser maker of the visitor.