### Feel The Power # Javascript Operators

## Arithmetic operators

JavaScript has the arithmetic operators +, -, *, /, and %. These operators function as the addition, subtraction, multiplication, division, and modulus operators, and operate very similarly to other languages.

``````var a = 12 + 5;    // 17
var b = 12 - 5;    // 7
var c = 12*5;      // 60
var d = 12/5;      // 2.4 - division results in floating point numbers.
var e = 12%5;      // 2 - the remainder of 12/5 in integer math is 2.``````

Some mathematical operations, such as dividing by zero, cause the returned variable to be one of the error values - for example, infinity, or NaN.

The return value of the modulus operator maintains the sign of the first operand.

The + and - operators also have unary versions, where they operate only on one variable. When used in this fashion, + returns the number representation of the object, while - returns its negative counterpart.

``````var a = "1";
var b = a;     // b = "1": a string
var c = +a;    // c = 1: a number
var d = -a;    // d = -1: a number``````

+ is also used as the string concatenation operator: If any of its arguments is a string or is otherwise not a number, any non-string arguments are converted to strings, and the 2 strings are concatenated. For example, 5 + [1, 2, 3] evaluates to the string "51, 2, 3". More usefully, str1 + " " + str2 returns str1 concatenated with str2, with a space between.

All other arithmetic operators will attempt to convert their arguments into numbers before evaluating. Note that unlike C or Java, the numbers and their operation results are not guaranteed to be integers.

## Bitwise operators

There are seven bitwise operators: &, |, ^, ~, >>, <<, and >>>.

These operators convert their operands to integers (truncating any floating point towards 0), and perform the specified bitwise operation on them. The logical bitwise operators, &, |, and ^, perform the andor, and xor on each individual bit and provides the return value. The ~ (not operator) inverts all bits within an integer, and usually appears in combination with the logical bitwise operators.

Two bit shift operators, >>, <<, move the bits in one direction that has a similar effect to multiplying or dividing by a power of two. The final bit-shift operator, >>>, operates the same way, but does not preserve the sign bit when shifting.

These operators are kept for parity with the related programming languages, but are unlikely to be used in most JavaScript programs.

## Assignment operators

The assignment operator = assigns a value to a variable. Primitive types, such as strings and numbers are assigned directly, however function and object names are just pointers to the respective function or object. In this case, the assignment operator only changes the reference to the object rather than the object itself. For example, after the following code is executed, "0, 1, 0" will be alerted, even though setA was passed to the alert, and setB was changed. This is, because they are two references to the same object.

``````setA = [ 0, 1, 2 ];
setB = setA;
setB = 0;

Similarly, after the next bit of code is executed, x is a pointer to an empty array.

``````z = ;
x = z;
z.pop();``````

All the above operators have corresponding assignment operators of the form operator=. For all of them, x operator= y is just a convenient abbreviation for x = x operator y.

Arithmetic Logical Shift
+= &= >>=
-= |= <<=
*= ^= >>>=
/=
%=

For example, a common usage for += is in a for loop

``````var element = document.getElementsByTagName('h2');
var i;
for (i = 0; i < element .length; i += 1) {
// do something with element [i]
}``````

## Increment operators

There are also the increment and decrement operators, ++ and --. a++ increments a and returns the old value of a. ++a increments a and returns the new value of a. The decrement operator functions similarly, but reduces the variable instead.

As an example, the last four lines all perform the same task:

``````var a = 1;
a = a + 1;
a += 1;
a++;
++a;``````

### Pre and post-increment operators

Increment operators may be applied before or after a variable. When they are applied before or after a variable, they are pre-increment or post-increment operators, respectively. The choice of which to use changes how they affect operations.

``````// increment occurs before a is assigned to b
var a = 1;
var b = ++a; // a = 2, b = 2;

// increment occurs to c after c is assigned to d
var c = 1;
var d = c++; // c = 2, d = 1;``````

Due to the possibly confusing nature of pre and post-increment behaviour, code can be easier to read, if the increment operators are avoided.

``````// increment occurs before a is assigned to b
var a = 1;
a += 1;
var b = a; // a = 2, b = 2;

// increment occurs to c after c is assigned to d
var c = 1;
var d = c;
c += 1; // c = 2, d = 1;``````

## Comparison operators

The comparison operators determine, if the two operands meet the given condition.

Operator Returns Notes
== true, if the two operands are equal May ignore operand's type
(e.g. a string as an integer)
=== true, if the two operands are identical Does not ignore operands' types, and only
returns true if they are the same type and value
!= true, if the two operands are not equal May ignore an operand's type
(e.g. a string as an integer)
!== true, if the two operands are not identical Does not ignore the operands' types, and only
returns false if they are the same type and value.
> true, if the first operand is greater than the second one
>= true, if the first operand is greater than or equal to the second one
< true, if the first operand is less than the second one
<= true, if the first operand is less than or equal to the second one

Be careful when using == and !=, as they may ignore the type of one of the terms being compared. This can lead to strange and non-intuitive situations, such as:

``````0 == '' // true
0 == '0' // true
false == 'false' // false; (''Boolean to string'')
false == '0' // true (''Boolean to string'')
false == undefined // false
false == null // false (''Boolean to null'')
null == undefined // true``````

For stricter compares use === and !==

``````0 === '' // false
0 === '0' // false
false === 'false' // false
false === '0' // false
false === undefined // false
false === null // false
null === undefined // false``````

## Logical operators

• && - and
• || - or
• ! - not

The logical operators are andor, and not. The && and || operators accept two operands and provides their associated logical result, while the third accepts one, and returns its logical negation. && and || are short circuit operators. If the result is guaranteed after evaluation of the first operand, it skips evaluation of the second operand.

Technically, the exact return value of these two operators is also equal to the final operand that it evaluated. Due to this, the && operator is also known as the guard operator, and the || operator is also known as the default operator.

``````function handleEvent(event) {
event = event || window.event;
var target = event.target || event.srcElement;
if (target && target.nodeType === 1 && target.nodeName === 'A') {
// ...
}
}``````

The ! operator determines the inverse of the given value, and returns the boolean: true values become false, or false values become true.

Note: JavaScript represents false by either a Boolean false, the number 0, an empty string, or the built in undefined or null type. Any other value is treated as true.

## Other operators

### ? :

The ? : operator (also called the "ternary" operator).

``var target = (a == b) ? c : d;``

Be cautious though in its use. Even though you can replace verbose and complex if/then/else chains with ternary operators, it may not be a good idea to do so. You can replace

``````if (p && q) {
return a;
} else {
if (r != s) {
return b;
} else {
if (t || !v) {
return c;
} else {
return d;
}
}
}``````

with

``````return (p && q) ? a
: (r != s) ? b
: (t || !v) ? c
: d``````

The above example is a poor coding style/practice. When other people edit or maintain your code, (which could very possibly be you,) it becomes much more difficult to understand and work with the code.

Instead, it is better to make the code more understandable. Some of the excessive conditional nesting can be removed from the above example.

``````if (p && q) {
return a;
}
if (r != s) {
return b;
}
if (t || !v) {
return c;
} else {
return d;
}``````

### delete

delete x unbinds x.

### new

new cl creates a new object of type cl. The cl operand must be a constructor function.

### instanceof

o instanceof c tests whether o is an object created by the constructor c.

### typeof

typeof x returns a string describing the type of x. Following values may be returned:

Type returns
boolean "boolean"
number "number"
null "object"
string "string"
undefined "undefined"
others "object"
#Javascript Operators Example #Javascript Operators Code #Javascript Operators Tutorial
RECENT TUTORIALS
CATEGORIES