Expressions in JavaScript evaluate to produce a value, and operators are the constructs that define how expressions are evaluated. Understanding the various types of operators and their usage is crucial for writing effective JavaScript code. This guide covers the primary categories of operators with detailed examples to ensure a comprehensive understanding.
Assignment Operators
Assignment operators assign values to variables. The most basic one is =
. There are also compound assignment operators that combine a binary operation and assignment in one.
Syntax and Examples:
let x = 10; // Assigns 10 to x
let y = x; // Assigns the value of x (10) to y
x += 5; // Equivalent to x = x + 5; x is now 15
x -= 3; // Equivalent to x = x - 3; x is now 12
x *= 2; // Equivalent to x = x * 2; x is now 24
x /= 4; // Equivalent to x = x / 4; x is now 6
x %= 3; // Equivalent to x = x % 3; x is now 0
x **= 2; // Equivalent to x = x ** 2; x is now 0
// Bitwise assignment operators
x &= 5; // Equivalent to x = x & 5
x |= 2; // Equivalent to x = x | 2
x ^= 3; // Equivalent to x = x ^ 3
x <<= 1; // Equivalent to x = x << 1
x >>= 1; // Equivalent to x = x >> 1
x >>>= 1; // Equivalent to x = x >>> 1
Comparison Operators
Comparison operators compare two values and return a boolean result. These operators can be used to test for equality, inequality, and relational comparisons.
Examples:
let a = 5, b = 10;
console.log(a == b); // false (equal to, type-converting)
console.log(a === b); // false (strict equal to, no type conversion)
console.log(a != b); // true (not equal to, type-converting)
console.log(a !== b); // true (strict not equal to, no type conversion)
console.log(a > b); // false (greater than)
console.log(a >= b); // false (greater than or equal to)
console.log(a < b); // true (less than)
console.log(a <= b); // true (less than or equal to)
// More examples
console.log('10' == 10); // true (type-converting comparison)
console.log('10' === 10); // false (no type conversion)
console.log(null == undefined); // true (type-converting comparison)
console.log(null === undefined); // false (strict comparison)
Arithmetic Operators
Arithmetic operators perform mathematical operations on numbers.
Examples:
let x = 10, y = 5;
console.log(x + y); // 15 (addition)
console.log(x - y); // 5 (subtraction)
console.log(x * y); // 50 (multiplication)
console.log(x / y); // 2 (division)
console.log(x % y); // 0 (remainder)
console.log(x ** y); // 100000 (exponentiation)
console.log(-x); // -10 (negation)
console.log(+y); // 5 (unary plus)
// Increment and Decrement
let z = 5;
console.log(z++); // 5 (returns 5, then increments to 6)
console.log(z); // 6
console.log(++z); // 7 (increments to 7, then returns 7)
console.log(z--); // 7 (returns 7, then decrements to 6)
console.log(z); // 6
console.log(--z); // 5 (decrements to 5, then returns 5)
Bitwise Operators
Bitwise operators perform operations on binary representations of numbers. These operators treat their operands as sets of 32 bits (zeros and ones), rather than as decimal, hexadecimal, or octal numbers.
Examples:
let x = 5, y = 3;
console.log(x & y); // 1 (bitwise AND)
console.log(x | y); // 7 (bitwise OR)
console.log(x ^ y); // 6 (bitwise XOR)
console.log(~x); // -6 (bitwise NOT)
console.log(x << 1); // 10 (left shift)
console.log(x >> 1); // 2 (right shift)
console.log(x >>> 1); // 2 (zero-fill right shift)
// Examples with binary
let a = 0b1010; // 10 in binary
let b = 0b1100; // 12 in binary
console.log(a & b); // 0b1000 (8 in decimal)
console.log(a | b); // 0b1110 (14 in decimal)
console.log(a ^ b); // 0b0110 (6 in decimal)
Logical Operators
Logical operators are used with boolean (logical) values. When they are used, they return a boolean value.
Examples:
let a = true, b = false;
console.log(a && b); // false (logical AND)
console.log(a || b); // true (logical OR)
console.log(!a); // false (logical NOT)
// More Examples
let x = 5;
console.log(x > 3 && x < 10); // true (both conditions true)
console.log(x > 3 || x > 10); // true (one condition true)
console.log(!(x > 3)); // false (negation of true)
BigInt Operators
BigInt operators perform operations on large integers. BigInt is a special numeric type that provides support for integers of arbitrary length.
Examples:
let x = 1234567890123456789012345678901234567890n;
let y = 9876543210987654321098765432109876543210n;
console.log(x + y); // BigInt addition
console.log(x * y); // BigInt multiplication
console.log(x / y); // BigInt division
console.log(x % y); // BigInt remainder
console.log(x ** 2n);// BigInt exponentiation
// Mixed Examples
let a = 10n;
let b = 3n;
console.log(a + b); // 13n
console.log(a - b); // 7n
console.log(a * b); // 30n
console.log(a / b); // 3n (BigInt division truncates the decimal part)
console.log(a % b); // 1n
console.log(-a); // -10n (negation)
String Operators
String operators concatenate strings.
Examples:
let str1 = "Hello";
let str2 = "World";
console.log(str1 + " " + str2); // "Hello World" (concatenation)
console.log(str1 += " there!"); // "Hello there!" (compound assignment)
// More Examples
let name = "John";
let greeting = "Hello, " + name + "!";
console.log(greeting); // "Hello, John!"
// String interpolation (ES6 feature)
let age = 30;
let message = `My name is ${name} and I am ${age} years old.`;
console.log(message); // "My name is John and I am 30 years old."
Conditional (Ternary) Operator
The conditional operator assigns a value based on a condition. It is the only JavaScript operator that takes three operands.
Syntax and Example:
let age = 18;
let access = (age >= 18) ? "Allowed" : "Denied";
console.log(access); // "Allowed"
// More Examples
let isMember = true;
let discount = isMember ? 10 : 5;
console.log(discount); // 10
let x = 10, y = 5;
let max = (x > y) ? x : y;
console.log(max); // 10
Comma Operator
The comma operator evaluates each of its operands (from left to right) and returns the value of the last operand.
Example:
let x = (2 + 3, 4 + 5);
console.log(x); // 9 (result of 4 + 5)
// More Examples
let a, b, c;
a = (b = 5, c = b + 10);
console.log(a); // 15
console.log(b); // 5
console.log(c); // 15
Unary Operators
Unary operators take a single operand/argument and perform various operations.
Examples:
let x = 10;
console.log(typeof x); // "number" (type of)
console.log(-x); // -10 (negation)
console.log(+x); // 10 (unary plus)
console.log(++x); // 11 (pre-increment)
console.log(x++); // 11 (post
-increment, returns 11, x becomes 12)
console.log(--x); // 11 (pre-decrement)
console.log(x--); // 11 (post-decrement, returns 11, x becomes 10)
console.log(delete x); // false (delete variable)
console.log(void x); // undefined (void operator)
console.log(typeof NaN); // "number"
// More Examples
let obj = { name: "Alice" };
console.log(delete obj.name); // true (deletes the property)
console.log(obj); // {}
let arr = [1, 2, 3];
console.log(delete arr[1]); // true (deletes the element but leaves an empty slot)
console.log(arr); // [1, empty, 3]
Relational Operators
Relational operators test the relationship between two values. The in
operator checks if a property exists in an object. The instanceof
operator checks if an object is an instance of a specific class or constructor.
Examples:
let x = 10, y = 5;
let obj = { x: 10, y: 5 };
console.log('x' in obj); // true (property 'x' exists in obj)
console.log('z' in obj); // false (property 'z' does not exist in obj)
console.log(0 in [1, 2, 3]); // true (array index 0 exists)
console.log(3 in [1, 2, 3]); // false (array index 3 does not exist)
class Car {}
let myCar = new Car();
console.log(myCar instanceof Car); // true (myCar is an instance of Car)
console.log(myCar instanceof Object); // true (myCar is an instance of Object)
let date = new Date();
console.log(date instanceof Date); // true (date is an instance of Date)
console.log(date instanceof Object); // true (date is an instance of Object)
// More Examples
function Person(name) {
this.name = name;
}
let john = new Person('John');
console.log(john instanceof Person); // true
console.log(john instanceof Object); // true
let str = "hello";
console.log(str instanceof String); // false (primitive string, not an instance of String object)
let strObj = new String("hello");
console.log(strObj instanceof String); // true
Conclusion
Understanding expressions and operators is fundamental to mastering JavaScript. From assignment and comparison operators to arithmetic and bitwise operations, each plays a crucial role in manipulating data and controlling program flow. Logical and conditional operators aid in decision-making, while string and BigInt operators expand the language's versatility. Unary and relational operators further enhance JavaScript's expressive power. Equipped with this knowledge, you can write more efficient and effective JavaScript code, making your programming more robust and versatile.
As we continue our journey in mastering JavaScript, our next topic delves into the world of functions and the nuances of strict mode. Functions are essential building blocks in JavaScript, providing modularity and reusability in your code, while strict mode helps catch errors early and enforce best practices. Stay tuned to learn how to define, call, and leverage advanced function concepts like closures and recursion, and how to write cleaner, more efficient code by adopting strict mode practices.