Operators are essential building blocks in JavaScript. They allow you to perform operations on values and variables. This comprehensive guide covers all JavaScript operators in detail.
You'll learn about assignment, arithmetic, comparison, logical, string, and other operators.
The article demonstrates how to use each operator properly. By the end, you'll have a solid understanding of JavaScript operators to write cleaner and more efficient code.
What are JavaScript Operators ? π€·πΌ
JavaScript operators allow you to perform operations on values and variables. Operators are essential in JavaScript for manipulating data, executing code conditionally, and controlling program flow. Mastering the various operator types is key to writing efficient JavaScript code.
Importance of JavaScript Operators π
Here are some key importance of JavaScript operators
π° Assignment Operators Operators like [=, +=, -=] : allow you to assign values to variables. This is crucial for storing data and updating values in your code.
π Arithmetic Operators Operators like [+, -, *, /, %] : allow you to perform basic math in JavaScript. You can calculate values, increment/decrement numbers, find remainders, etc. Math is key for many programming tasks.
π Comparison Operators Operators like [==, ===, >, <] : let you compare values and check for equality. This is vital for decision-making and controlling program flow based on conditions.
π§ Logical Operators Logical operators like [&&, ||, !] : allow you to combine comparisons and conditions. This lets you create complex logic by testing multiple cases and conditions. Being able to execute precise logical operations is important.
JavaScript Operators Reference
The following section provides an in-depth overview of the different JavaScript operator types including assignment, comparison, arithmetic, bitwise, logical, and more. The syntax and usage of each operator is explained.
Arithmetic Operators ποΈ
- Subtraction - : Deducts the second number from the first.
let result = 7 - 4;
console.log(result); // Outputs: 3
- Multiplication * : Multiplies two numbers.
let result = 3 * 4;
console.log(result); // Outputs: 12
- Division / : Divides the first number by the second.
let result = 8 / 4;
console.log(result); // Outputs: 2
- Modulus % : Returns the remainder after division.
let result = 8 % 3;
console.log(result); // Outputs: 2
- Increment ++ : Increases the number by one.
let num = 4;
num++;
console.log(num); // Outputs: 5
- Decrement -- : Reduces the number by one.
let num = 4;
num--;
console.log(num); // Outputs: 3
- Exponentiation ** : Raises the first number to the power of the second number.
let result = 3 ** 2;
console.log(result); // Outputs: 9
- Unary negation - : Negates the number.
let result = -3;
console.log(result); // Outputs: -3
- Unary plus + : Converts the operand into a number.
let result = +"3";
console.log(result); // Outputs: 3
Comparison Operators βοΈ
- Equal == : Checks if values are equal, type conversion may occur.
let isEqual = '5' == 5;
console.log(isEqual); // Outputs: true
- Not equal != : Checks if values are not equal.
let isNotEqual = 5 != '6';
console.log(isNotEqual); // Outputs: true
- Strict equal === : Checks if values and types are equal.
let isStrictlyEqual = '5' === 5;
console.log(isStrictlyEqual); // Outputs: false
- Strict not equal !== : Checks if values and types are not equal.
let isStrictlyNotEqual = 5 !== '5';
console.log(isStrictlyNotEqual); // Outputs: true
- Greater than > : Checks if the first value is greater than the second.
let isGreater = 6 > 3;
console.log(isGreater); // Outputs: true
- Less than < : Checks if the first value is less than the second.
let isLess = 3 < 6;
console.log(isLess); // Outputs: true
- Greater than or equal >= : Checks if the first value is greater than or equal to the second.
let isGreaterOrEqual = 6 >= 3;
console.log(isGreaterOrEqual); // Outputs: true
- Less than or equal <= : Checks if the first value is less than or equal to the second.
let isLessOrEqual = 3 <= 6;
console.log(isLessOrEqual); // Outputs: true
Logical Operators π
- Logical AND && : Returns true if both conditions are true.
let result = (6 > 3) && (7 < 10);
console.log(result); // Outputs: true
- Logical OR || : Returns true if at least one condition is true.
let result = (6 < 3) || (7 < 10);
console.log(result); // Outputs: true
- Logical NOT ! : Inverts the truthiness of a value.
let result = !(6 > 3);
console.log(result); // Outputs: false
- Nullish coalescing ?? : Returns the right operand if the left is null or undefined.
let name = null;
let displayName = name ?? "Guest";
console.log(displayName); // Outputs: "Guest"
Assignment Operators π₯
- Assignment = : Assigns a value to a variable.
let age = 25;
console.log(age); // Outputs: 25
- Addition assignment += : Adds and assigns.
let num = 5;
num += 3;
console.log(num); // Outputs: 8
- Subtraction assignment -= : Subtracts and assigns.
let num = 8;
num -= 3;
console.log(num); // Outputs: 5
- Multiplication assignment *= : Multiplies and assigns.
let num = 4;
num *= 3;
console.log(num); // Outputs: 12
- Division assignment /= : Divides and assigns.
let num = 12;
num /= 3;
console.log(num); // Outputs: 4
- Remainder assignment %= : Assigns the remainder of a division.
let num = 13;
num %= 5;
console.log(num); // Outputs: 3
- Exponentiation assignment **= : Raises to a power and assigns.
let num = 3;
num **= 3;
console.log(num); // Outputs: 27
- Left shift assignment <<= : Shifts left and assigns.
let num = 5; // Binary: 101 num <<= 1; console.log(num); // Outputs: 10, Binary: 1010
- Right shift assignment >>= : Shifts right and assigns.
let num = 5; // Binary: 101 num >>= 1; console.log(num); // Outputs: 2, Binary: 10
- Unsigned right shift assignment >>>= : Shifts right without sign and assigns.
let num = -5;
num >>>= 1;
console.log(num); // Outputs a large number due to unsigned shift
- Bitwise AND assignment &= : Performs a bitwise AND and assigns.
let num = 5; // Binary: 101
num &= 3; // Binary: 011
console.log(num); // Outputs: 1, Binary: 001
- Bitwise XOR assignment ^= : Performs a bitwise XOR and assigns.
let num = 5; // Binary: 101
num ^= 3; // Binary: 011
console.log(num); // Outputs: 6, Binary: 110
- Bitwise OR assignment |= : Performs a bitwise OR and assigns.
let num = 5; // Binary: 101
num |= 3; // Binary: 011
console.log(num); // Outputs: 7, Binary: 111
- Logical AND assignment &&= : Assigns the right value if the left is truthy.
let value = "Hello";
value &&= "World";
console.log(value); // Outputs: "World"
- Logical OR assignment ||= : Assigns the right value if the left is falsy.
let value = "";
value ||= "World";
console.log(value); // Outputs: "World"
- Nullish assignment ??= : Assigns the right value if the left is null or undefined.
let name = null;
name ??= "Guest";
console.log(name); // Outputs: "Guest"
Bitwise and Bit Shift Operators π₯Ά
- Bitwise AND & : Returns a number with bits set where both numbers have bits set.
let result = 5 & 3; // 101 & 011
console.log(result); // Outputs: 1
- Bitwise OR | : Returns a number with bits set where one of the numbers has bits set.
let result = 5 | 3; // 101 | 011
console.log(result); // Outputs: 7
- Bitwise XOR ^ : Returns a number with bits set where only one of the numbers has bits set.
let result = 5 ^ 3; // 101 ^ 011
console.log(result); // Outputs: 6
- Bitwise NOT ~ : Inverts the bits of a number.
let result = ~5; // ~101
console.log(result); // Outputs: -6
- Left shift << : Shifts the bits of the first operand to the left by the number of positions specified by the second operand.
let result = 5 << 1; // 101 << 1
console.log(result); // Outputs: 10
- Sign propagating right shift >> : Shifts the bits of the first operand to the right by the number of positions specified by the second operand.
let result = 5 >> 1; // 101 >> 1
console.log(result); // Outputs: 2
- Zero fill right shift >>> : Shifts the bits of the first operand to the right without sign propagation.
let result = -5 >>> 1;
console.log(result); // Outputs a large number due to unsigned shift
Relational Operators πͺ
- in: Determines if an object has a specific property.
let obj = {key: "value"};
console.log("key" in obj); // Outputs: true
- instanceof : Determines if an object is an instance of a specific constructor.
let arr = [];
console.log(arr instanceof Array); // Outputs: true
Conditional (Ternary) Operator π₯Έ
- (condition ? value1 : value2) : Returns one of two values based on a condition.
let age = 18;
let status = age >= 18 ? "adult" : "minor";
console.log(status); // Outputs: "adult"
Spread and Rest Operators π΄
- typeof : Returns a string indicating the type of a variable.
let str = "Hello";
console.log(typeof str); // Outputs: "string"
- instanceof : Determines if an object is an instance of a specific constructor.
let date = new Date();
console.log(date instanceof Date); // Outputs: true
- Spread ... : Expands an array or object in places where multiple elements or properties are expected.
let arr = [1, 2, 3];
let newArr = [...arr, 4, 5];
console.log(newArr); // Outputs: [1, 2, 3, 4, 5]
- Rest ... : Collects multiple elements into an array.
function collect(...args) {
console.log(args);
}
collect(1, 2, 3); // Outputs: [1, 2, 3]
Destructuring Assignment Operators π’
- Array destructuring [...] : Allows unpacking of elements from arrays.
let [a, b, ...rest] = [1, 2, 3, 4, 5];
console.log(a, b, rest); // Outputs: 1 2 [3, 4, 5]
- Object destructuring {...} : Allows unpacking of properties from objects.
let {name, age, ...details} = {name: "John", age: 25, country: "US"};
console.log(name, age, details); // Outputs: John 25 {country: "US"}Other Operators
Other Operators πͺ
- Comma (,) : Evaluates multiple expressions and returns the last one.
let x = (5, 6);
console.log(x); // Outputs: 6
- delete : Deletes an object's property.
let obj = {name: "John"};
delete obj.name;
console.log(obj); // Outputs: {}
- new : Creates an instance of a constructor.
function Person(name) {
this.name = name;
}
let person = new Person("John");
console.log(person.name); // Outputs: "John"
- this : Refers to the current object.
function Person(name) {
this.name = name;
this.sayName = function() {
console.log(this.name);
}
}
let person = new Person("John");
person.sayName(); // Outputs: "John"
- super : Refers to the parent object.
class Child extends Parent {
constructor() {
super();
}
}
- void : Discards a value, often used to retrieve the undefined primitive value.
console.log(void 0); // Outputs: undefined
- await : Waits for a Promise to resolve or reject.
async function fetchData() {
let data = await fetch("https://api.example.com/data");
return data.json();
}
- yield : Pauses and resumes a generator function.
function* generatorFunc() {
yield 1;
yield 2;
return 3;
}
- yield* : Delegates to another generator function.
function* generatorA() {
yield 1;
yield* generatorB();
}
function* generatorB() {
yield 2;
yield 3;
}
Thatβs it! We have successfully covered the comprehensive operators in JavaScript!
Conclusion π
JavaScript operators allow you to manipulate values and execute code in a variety of ways. Whether you need to do math, concatenate strings, compare values, or accomplish other tasks, there are operators available to suit your needs.
Learning how to properly use operators can help you write cleaner, more efficient JavaScript code. With practice, you'll be able to leverage operators to their full potential for any JavaScript project.