Wednesday, February 19, 2025

JavaScript, special operators













What are some special operators introduced in modern JavaScript?


Modern JavaScript has introduced several new operators that provide more flexibility and efficiency in the language. Here are some of the key special operators:

Nullish Coalescing Operator (??):

This operator returns the right-hand operand when the left-hand operand is null or undefined, otherwise, it returns the left-hand operand.


let a = null;
let b = "Hello";
console.log(a ?? b); // "Hello"
Optional Chaining (?.):

This allows safe navigation through properties of objects that may be null or undefined. If any part of the chain is null or undefined, it short-circuits and returns undefined instead of throwing an error.


let user = { address: { street: "Main St" } };
console.log(user?.address?.street); // "Main St"
console.log(user?.phone?.number); // undefined
Logical Assignment Operators (&&=, ||=, ??=):

These combine logical operators with assignment, making it easier to assign values conditionally.


let x = 0;
x ||= 5; // If x is falsy, assign 5
console.log(x); // 5

let y = null;
y ??= 10; // If y is null or undefined, assign 10
console.log(y); // 10

let z = true;
z &&= false; // If z is truthy, assign false
console.log(z); // false
Spread (...) and Rest (...) Operators:

The spread operator is used to expand or unpack elements of an iterable (e.g., arrays, objects).
The rest operator collects multiple elements into a single array.


// Spread (arrays and objects)
let arr = [1, 2, 3];
let newArr = [...arr, 4, 5]; // [1, 2, 3, 4, 5]

let obj = { a: 1, b: 2 };
let newObj = { ...obj, c: 3 }; // { a: 1, b: 2, c: 3 }

// Rest (function arguments and destructuring)
function sum(...args) {
  return args.reduce((acc, curr) => acc + curr, 0);
}

let { a, ...rest } = obj;
console.log(rest); // { b: 2 }
BigInt (n suffix):

BigInt is a new primitive type for working with arbitrarily large integers, beyond the limitations of Number.


const bigNumber = 1234567890123456789012345678901234567890n;
console.log(bigNumber + 10n); // 1234567890123456789012345678901234567900n
Promise.allSettled:

While not exactly an operator, Promise.allSettled is a method that helps handle multiple promises, returning an array of objects with the status of each promise.


Promise.allSettled([Promise.resolve(1), Promise.reject("error")])
  .then(results => console.log(results)); 
These new operators and methods help developers write cleaner, more expressive, and error-resistant code.





No comments:

Post a Comment

Hot Topics