CS Basics: Operators in JavaScript Pt. 2

A deeper look at advanced JavaScript operators - including bitwise, typeof, delete, in, instanceof, and void - with clear examples and explanations.

Originally written by Carl Mills · December 19, 2017

Bitwise Operators

Bitwise operators work on binary representations of numbers. Each operand is converted to binary, the operation runs at the bit level, then the result is converted back to an integer.

Operator Known As Example Binary Operation Result (Binary) Decimal
& AND x = 5 & 1 0101 & 0001 0001 1
| OR x = 5 | 1 0101 | 0001 0101 5
~ NOT x = ~5 ~0101 1010 10
^ XOR x = 5 ^ 1 0101 ^ 0001 0100 4
<< Left Shift x = 5 << 1 0101 << 1 1010 10
>> Right Shift x = 5 >> 1 0101 >> 1 0010 2

typeof Operator

Returns the type of a variable, object, function, or expression.

typeof "John"                 // "string"
typeof 3.14                  // "number"
typeof NaN                   // "number"
typeof false                 // "boolean"
typeof [1,2,3,4]             // "object"
typeof {name:'John', age:34} // "object"
typeof new Date()            // "object"
typeof function() {}         // "function"
typeof myCar                 // "undefined" (if not declared)
typeof null                  // "object"

delete Operator

Deletes a property from an object.

var person = {firstName: "Dave", lastName: "Doe", age: 67, eyeColor: "blue"};
delete person.age;

// Now the object is:
{firstName: "Dave", lastName: "Doe", eyeColor: "blue"}

in Operator

Checks whether a property exists in an object or index in an array.

Arrays
var cars = ["Saab", "Volvo", "BMW"];
"Saab" in cars   // false (must use index)
0 in cars        // true
4 in cars        // false
"length" in cars // true
Objects
var person = {firstName: "John", lastName: "Doe", age: 50};
"firstName" in person // true
"age" in person       // true
Predefined Objects
"PI" in Math       // true
"NaN" in Number    // true
"length" in String // true

instanceof Operator

Returns true if an object is an instance of a specified class or constructor.

var cars = ["Saab", "Volvo", "BMW"];

cars instanceof Array  // true
cars instanceof Object // true
cars instanceof String // false
cars instanceof Number // false

void Operator

Evaluates an expression and returns undefined. Often used to prevent a link from navigating while still running code.

<a href="javascript:void(0);">Useless link</a>

<a href="javascript:void(document.body.style.backgroundColor='red');">
Click me to change the background colour
</a>

That's All for JavaScript Operators

This concludes the full breakdown of JavaScript operators - from basic arithmetic and comparison to bitwise, type checking, and object property control.

Continue to the Next CS Basics Topic →