(click anywhere to close)

# [JavaScript] Advanced Operators

category: Website | course: Advanced Javascript | difficulty:

We’ve already seen the basic operators `+ - / * %`, which is often all that you need, but there are certain bitwise operators that can simplify your life. We’ll also look at operators that work on only one value, not two.

## Bitwise Operators

To be able to use a bitwise operator, JavaScript converts your operands to 32-bit integer numbers, consisting of only zeros and ones. Each bit in the first operand is paired with the corresponding bit in the second one, and the operator is applied. This means that the result is again a 32-bit number.

 Name Symbol Description Bitwise AND a `&` b Returns one if corresponding bits are both ones Bitwise OR a `|` b Returns zero if corresponding bits are both zeros Bitwise XOR a `^` b Returns a zero if corresponding bits are the same, returns a one if they are different. Bitwise NOT `~` a Inverts the bits of its operand (zeros become ones, and vice versa) Left Shift a `<<` b Shifts a to the left with b bits, shifting in zeros from the right Right Shift a `>>` b Shifts a tot the right with b bits, discarding bits shifted off Zero-fill Right Shift a `>>>` b Shifts a to the right with b bits, discarding bits shifted off, and shifting in zeros from the left
```var x = 10; 	//x is 00000000000000000000000000001010
var y = x << 2; //y is 00000000000000000000000000101000, or 40
var z = ~y;		//z is 11111111111111111111111111010111, or -41
```

In JavaScript binary representation, if the left-most bit is set to one, it’s a negative number.

If you can’t immediately see any use for these, I suggest you look a bit into binary numbers. If you know how they work, you can often find ways to simplify your life by using these binary operators. For example, `~~a` is the same as `Math.floor(a)`, but faster and less typing.

## Relational Operators

The `in` operator checks whether a certain property or index exists within an object or array. The syntax is

`if(propNameOrNumber in objectName) { statements }`

```var obj = {name:"Juan",color:"Red"};
if("age" in obj) {
//This will not execute
}
```

The `instanceof` operator checks whether a specific object is of a certain object type. The syntax is

`if(objectName instanceof objectType) { statements } `

```if([1,2,3] instanceof Array) {
console.log("Yes it is!"); //This one will execute
} else {
console.log("Fail!");
}
```

The spread operator allows an expression with multiple values to be expanded wherever multiple arguments (function calls) or multiple elements (array literals) are expected. The syntax is `…expression`.

```var arrUno = [2,3,4];
var arrDuo = [1,...arrUno,5]; //arrDuo is [1,2,3,4,5]
```
CONTINUE WITH THIS COURSE
Do you like my tutorials?
To keep this site running, donate some motivational food!
Crisps
(€2.00)
Chocolate Milk
(€3.50)
Pizza
(€5.00)