JavaScript Objects, Unary Operators and Logical Operators JavaScript uses the increment (++) and decrement (--) on all data types.

Putting the operator before the variable will change the value before the final evaluation of the statement.

Putting the operator after the variable will change the value after the evaluation.

var x = 25;
y = ++x + 10;  // x = 26, y = 36

var x = 25;
y = x++ + 10;  // x = 26, y = 35

var x = 25;
y = --x + 10;  // x = 24, y = 34

var x = 25;
y = x-- + 10;  // x = 24, y = 35

Using the increment/decrement operator on a string first converts the value to a number and then performs the operation. If the string is not a valid number after conversion, it will give a NaN value.

If the data type of the variable is a boolean, it’s first converted to zero or one and then incremented/decremented.

Floating points increment/decrement as expected: by adding/subtracting 1.

Objects are first converted to a value with the ValueOf() method. It is converted from an object to a number.

Using the plus sign (+) in front of a variable will convert the variable to a number.

Using the minus sign (-) in front of a variable will convert the variable to a number and then negate it.

var b = "10";
c = +b;  //b = "10", c = 10
c = -b;  //b = "10", c = -10

The exclamation point (!) is the Logical ‘Not’ operator. Two exclamation points (!!) is the same as Boolean() to cast the data as a Boolean variable. The first exclamation point converts the data type to Boolean and negates it. The second ‘Not’ negates it again bringing it to it’s original value.

Since the Logical Or operator (||) is short-circuited, meaning that it never evaluates the second object if the first is true, you can use something like the following to assign variables:

var myvar = firstvar || secondvar;

In this code, the firstvar is assigned if it’s available. If not, the second variable is assigned.

Scroll to Top