JavaScript Operators

This document provides a comprehensive guide to JavaScript operators, explaining various types of operators such as arithmetic, assignment, comparison, logical, bitwise, string, unary, conditional, comma, nullish coalescing, and nullish assignment operators.

Introduction to Operators

What Are Operators?

Operators are symbols or keywords that perform operations on variables and values in programming languages. Think of operators as tools in a kitchen; just like how you use a knife to cut vegetables, you use operators to manipulate data. Operators are the building blocks of almost all programming languages, as they allow you to perform a wide range of tasks, from simple calculations to complex data manipulations. In JavaScript, operators help you assign values, compare values, perform arithmetic operations, and much more.

Types of Operators

JavaScript offers a rich set of operators, each serving a unique purpose. We will explore the different types of operators available in JavaScript, including arithmetic, assignment, comparison, logical, bitwise, string, unary, ternary, comma, nullish coalescing, and nullish assignment operators.

Arithmetic Operators

Arithmetic operators are used to perform mathematical operations on numbers.

Addition Operator

The addition operator (+) is used to add two or more numbers together. For example:

let x = 5;
let y = 10;
let sum = x + y;  // sum is 15
console.log(sum);  // Output: 15

In this example, the addition operator is used to add the values of x and y, and the result is stored in the variable sum.

Subtraction Operator

The subtraction operator (-) is used to subtract the second operand from the first operand. For example:

let x = 15;
let y = 5;
let difference = x - y;  // difference is 10
console.log(difference);  // Output: 10

In this example, y is subtracted from x, and the result is stored in the variable difference.

Multiplication Operator

The multiplication operator (*) is used to multiply two numbers together. For example:

let x = 10;
let y = 3;
let product = x * y;  // product is 30
console.log(product);  // Output: 30

In this example, x is multiplied by y, and the result is stored in the variable product.

Division Operator

The division operator (/) is used to divide the first operand by the second operand. For example:

let x = 20;
let y = 4;
let quotient = x / y;  // quotient is 5
console.log(quotient);  // Output: 5

In this example, x is divided by y, and the result is stored in the variable quotient.

Remainder Operator

The remainder operator (%) returns the remainder of the division of two operands. For example:

let x = 20;
let y = 3;
let remainder = x % y;  // remainder is 2
console.log(remainder);  // Output: 2

In this example, the remainder of x divided by y is calculated and stored in the variable remainder.

Increment Operator

The increment operator (++) increases the value of a variable by 1. For example:

let counter = 5;
counter++;  // counter is 6
console.log(counter);  // Output: 6

In this example, the counter variable is incremented by 1 using the increment operator.

Decrement Operator

The decrement operator (--) decreases the value of a variable by 1. For example:

let counter = 5;
counter--;  // counter is 4
console.log(counter);  // Output: 4

In this example, the counter variable is decremented by 1 using the decrement operator.

Exponentiation Operator

The exponentiation operator (**) raises the first operand to the power of the second operand. For example:

let base = 2;
let exponent = 3;
let power = base ** exponent;  // power is 8
console.log(power);  // Output: 8

In this example, base is raised to the power of exponent, and the result is stored in the variable power.

Assignment Operators

Assignment operators are used to assign values to variables.

Simple Assignment

The simple assignment operator (=) assigns the value of the right operand to the left operand. For example:

let x = 10;
console.log(x);  // Output: 10

In this example, the value 10 is assigned to the variable x.

Addition Assignment

The addition assignment operator (+=) adds the value of the right operand to the variable on the left and assigns the result to the variable. For example:

let x = 10;
x += 5;  // x is now 15
console.log(x);  // Output: 15

In this example, 5 is added to x, and the result is stored back in x.

Subtraction Assignment

The subtraction assignment operator (-=) subtracts the value of the right operand from the variable on the left and assigns the result to the variable. For example:

let x = 10;
x -= 5;  // x is now 5
console.log(x);  // Output: 5

In this example, 5 is subtracted from x, and the result is stored back in x.

Multiplication Assignment

The multiplication assignment operator (*=) multiplies the value of the right operand with the variable on the left and assigns the result to the variable. For example:

let x = 10;
x *= 5;  // x is now 50
console.log(x);  // Output: 50

In this example, x is multiplied by 5, and the result is stored back in x.

Division Assignment

The division assignment operator (/=) divides the variable on the left by the value of the right operand and assigns the result to the variable. For example:

let x = 20;
x /= 5;  // x is now 4
console.log(x);  // Output: 4

In this example, x is divided by 5, and the result is stored back in x.

Remainder Assignment

The remainder assignment operator (%=) divides the variable on the left by the value of the right operand, assigns the remainder to the variable on the left. For example:

let x = 20;
x %= 3;  // x is now 2
console.log(x);  // Output: 2

In this example, the remainder of x divided by 3 is calculated and stored back in x.

Exponentiation Assignment

The exponentiation assignment operator (**=) raises the variable on the left to the power of the right operand and assigns the result to the variable on the left. For example:

let x = 2;
x **= 3;  // x is now 8
console.log(x);  // Output: 8

In this example, x is raised to the power of 3, and the result is stored back in x.

Comparison Operators

Comparison operators are used to compare two values and return a Boolean value (true or false).

Equal to (==)

The equality operator (==) checks if two values are equal without considering their types. For example:

let a = 10;
let b = "10";
let result = a == b;  // result is true
console.log(result);  // Output: true

In this example, a and b are compared using the equality operator. Although b is a string, the equality operator returns true because the values are equal when type conversion is taken into account.

Not Equal to (!=)

The not equal operator (!=) checks if two values are not equal. For example:

let a = 10;
let b = 15;
let result = a != b;  // result is true
console.log(result);  // Output: true

In this example, a and b are compared using the not equal operator. Since a is not equal to b, the result is true.

Strict Equal to (===)

The strict equality operator (===) checks if two values are equal and of the same type. For example:

let a = 10;
let b = "10";
let result = a === b;  // result is false
console.log(result);  // Output: false

In this example, a and b are compared using the strict equality operator. The result is false because although the values are the same, their types (number and string) are different.

Strict Not Equal to (!==)

The strict not equal operator (!==) checks if two values are not equal or of different types. For example:

let a = 10;
let b = "10";
let result = a !== b;  // result is true
console.log(result);  // Output: true

In this example, a and b are compared using the strict not equal operator. The result is true because the types of a and b are different.

Greater Than (>)

The greater than operator (>) checks if the left operand is greater than the right operand. For example:

let x = 10;
let y = 5;
let result = x > y;  // result is true
console.log(result);  // Output: true

In this example, x is greater than y, so the result is true.

Less Than (<)

The less than operator (<) checks if the left operand is less than the right operand. For example:

let x = 5;
let y = 10;
let result = x < y;  // result is true
console.log(result);  // Output: true

In this example, x is less than y, so the result is true.

Greater Than or Equal to (>=)

The greater than or equal to operator (>=) checks if the left operand is greater than or equal to the right operand. For example:

let x = 10;
let y = 10;
let result = x >= y;  // result is true
console.log(result);  // Output: true

In this example, x is equal to y, so the result is true.

Less Than or Equal to (<=)

The less than or equal to operator (<=) checks if the left operand is less than or equal to the right operand. For example:

let x = 5;
let y = 10;
let result = x <= y;  // result is true
console.log(result);  // Output: true

In this example, x is less than y, so the result is true.

Logical Operators

Logical operators are used to determine the logic between variables or values.

Logical AND (&&)

The logical AND operator (&&) returns true if both operands are true. For example:

let p = true;
let q = false;
let result = p && q;  // result is false
console.log(result);  // Output: false

In this example, since p and q are not both true, the result is false.

Logical OR (||)

The logical OR operator (||) returns true if any of the operands is true. For example:

let p = true;
let q = false;
let result = p || q;  // result is true
console.log(result);  // Output: true

In this example, since p is true, the result is true.

Logical NOT (!)

The logical NOT operator (!) inverts the Boolean value of an operand. For example:

let p = true;
let result = !p;  // result is false
console.log(result);  // Output: false

In this example, the logical NOT operator inverts the value of p.

Bitwise Operators

Bitwise operators operate on 32-bit numbers. They treat numbers as a sequence of 32 bits and perform operations on each bit.

Bitwise AND (&)

The bitwise AND operator (&) compares each bit of its operands and returns 1 if both bits are 1; otherwise, it returns 0. For example:

let a = 5;  // 0101 in binary
let b = 3;  // 0011 in binary
let result = a & b;  // result is 1 (0001 in binary)
console.log(result);  // Output: 1

In this example, the bitwise AND operation is performed on a and b, and the result is stored in result.

Bitwise OR (|)

The bitwise OR operator (|) compares each bit of its operands and returns 1 if at least one bit is 1; otherwise, it returns 0. For example:

let a = 5;  // 0101 in binary
let b = 3;  // 0011 in binary
let result = a | b;  // result is 7 (0111 in binary)
console.log(result);  // Output: 7

In this example, the bitwise OR operation is performed on a and b, and the result is stored in result.

Bitwise XOR (^)

The bitwise XOR operator (^) compares each bit of its operands and returns 1 if the bits are different; otherwise, it returns 0. For example:

let a = 5;  // 0101 in binary
let b = 3;  // 0011 in binary
let result = a ^ b;  // result is 6 (0110 in binary)
console.log(result);  // Output: 6

In this example, the bitwise XOR operation is performed on a and b, and the result is stored in result.

Bitwise NOT (~)

The bitwise NOT operator (~) inverts all the bits of its operand. For example:

let a = 5;  // 0000 0000 0000 0000 0000 0000 0000 0101 in binary
let result = ~a;  // result is -6 (1111 1111 1111 1111 1111 1111 1111 1010 in binary)
console.log(result);  // Output: -6

In this example, the bitwise NOT operation is performed on a, and the result is stored in result.

Left Shift (<<)

The left shift operator (<<) shifts the bits of the left operand to the left by the number of positions specified by the right operand. For example:

let a = 5;  // 0101 in binary
let result = a << 1;  // result is 10 (1010 in binary)
console.log(result);  // Output: 10

In this example, the bits of a are shifted to the left by 1 position, and the result is stored in result.

Right Shift (>>)

The right shift operator (>>) shifts the bits of the left operand to the right by the number of positions specified by the right operand. For example:

let a = 10;  // 1010 in binary
let result = a >> 1;  // result is 5 (0101 in binary)
console.log(result);  // Output: 5

In this example, the bits of a are shifted to the right by 1 position, and the result is stored in result.

Unsigned Right Shift (>>>)

The unsigned right shift operator (>>>) is similar to the right shift operator, but the leftmost bits are filled with 0s instead of copying the sign bit. For example:

let a = -10;  // 1111 1111 1111 1111 1111 1111 1111 0110 in binary
let result = a >>> 1;  // result is 2147483643 (0111 1111 1111 1111 1111 1111 1111 1011 in binary)
console.log(result);  // Output: 2147483643

In this example, the bits of a are shifted to the right by 1 position, and the leftmost bits are filled with 0s.

String Operators

String operators are used to manipulate strings.

Concatenation Operator (+)

The concatenation operator (+) concatenates two or more strings. For example:

let firstName = "John";
let lastName = "Doe";
let fullName = firstName + " " + lastName;  // fullName is "John Doe"
console.log(fullName);  // Output: John Doe

In this example, the + operator is used to concatenate firstName and lastName with a space in between.

Spread Operator (...)

The spread operator (...) is used to expand an iterable (such as an array or object) into its individual elements. For example:

let arr1 = [1, 2, 3];
let arr2 = [...arr1, 4, 5];  // arr2 is [1, 2, 3, 4, 5]
console.log(arr2);  // Output: [1, 2, 3, 4, 5]

In this example, the spread operator (...) is used to expand arr1 and include it in arr2 along with additional elements.

Unary Operators

Unary operators are operators that operate on a single operand.

typeof

The typeof operator returns the type of a variable. For example:

let str = "Hello, World!";
let result = typeof str;  // result is "string"
console.log(result);  // Output: string

In this example, the typeof operator is used to check the type of the variable str.

delete (Used in Objects)

The delete operator removes a property from an object. For example:

let person = {
  firstName: "John",
  lastName: "Doe"
};

delete person.lastName;  // lastName is removed from the person object
console.log(person);  // Output: { firstName: "John" }

In this example, the delete operator is used to remove the lastName property from the person object.

void

The void operator evaluates an expression without returning a value. For example:

void (0);  // undefined
void someFunction();  // evaluates someFunction but hasn't a return value

In this example, the void operator is used to evaluate an expression without returning a value.

Unary Plus (+)

The unary plus operator (+) attempts to convert the operand into a number. For example:

let x = "10";
let y = +x;  // y is 10
console.log(y);  // Output: 10

In this example, the unary plus operator is used to convert the string x to a number.

Unary Negation (-)

The unary negation operator (-) negates the value of the operand. For example:

let x = 10;
let y = -x;  // y is -10
console.log(y);  // Output: -10

In this example, the unary negation operator is used to negate the value of x.

Ternary (Conditional) Operator

The ternary operator (condition ? exprIfTrue : exprIfFalse) is a shorthand for an if-else statement. For example:

let age = 18;
let canVote = (age >= 18) ? "Yes" : "No";  // canVote is "Yes"
console.log(canVote);  // Output: Yes

In this example, the ternary operator checks if age is greater than or equal to 18. If the condition is true, "Yes" is assigned to canVote; otherwise, "No" is assigned.

Comma Operator

The comma operator (,) allows you to execute multiple expressions and returns the value of the last expression. For example:

let x = (10, 20, 30);  // x is 30
console.log(x);  // Output: 30

In this example, the comma operator evaluates 10, 20, and 30, and the value of the last expression, 30, is assigned to x.

Nullish Coalescing Operator (??)

The nullish coalescing operator (??) returns the right operand when the left operand is null or undefined; otherwise, it returns the left operand. For example:

let name;
let displayName = name ?? "Guest";  // displayName is "Guest"
console.log(displayName);  // Output: Guest

In this example, since name is undefined, the nullish coalescing operator (??) returns the right operand, "Guest".

Nullish Assignment Operator (??=)

The nullish assignment operator (??=) assigns the value of the right operand to the left operand only if the left operand is null or undefined. For example:

let name;
name ??= "Guest";  // name is "Guest"
console.log(name);  // Output: Guest

In this example, since name is undefined, the nullish assignment operator (??=) assigns "Guest" to name.

These examples demonstrate the usage of different operators in JavaScript. Each operator serves a specific purpose, and understanding them is crucial for writing efficient and correct JavaScript code. Operators allow you to perform a variety of tasks, from simple calculations to complex data manipulations, making them an essential part of the JavaScript language. As you become more comfortable with JavaScript, you will find that operators are used in almost every line of code you write.