Topic 013: WeakSets, Nullish Coalescing, and Optional Chaining in JS
we’ll explore three key concepts in JavaScript that are valuable for memory management, logical operations, and working with potentially undefined properties. These concepts are WeakSets, the Nullish Coalescing Operator (??
), and the Optional Chaining Operator (?.
).
WeakSets are a unique data structure in JavaScript designed specifically for holding objects. Unlike regular Set
objects, a WeakSet
allows the JavaScript engine to automatically remove entries when there are no other references to the objects, helping with memory management through a process called garbage collection.
Here’s a breakdown of the key features of WeakSets:
WeakSet
becomes unreachable (meaning no other references exist), the object is automatically removed from the set. This makes WeakSets
useful in scenarios where you don’t want objects to prevent their own garbage collection.Set
.Example from the image:
const weakSet = new WeakSet();
const obj1 = {};
const obj2 = {};
weakSet.add(obj1);
weakSet.add(obj2);
console.log(weakSet.has(obj1)); // true
In this example, two objects, obj1
and obj2
, are added to the WeakSet. If obj1
becomes unreachable (i.e., no other reference to it exists), it will automatically be removed from weakSet
.
WeakSets are ideal in situations where you want to track objects weakly—allowing their memory to be freed up when no other parts of the code need them. This helps optimize memory usage in long-running applications.
??
)The nullish coalescing operator (??
) is used to assign a default value when the left-hand side is either null
or undefined
. This operator differs from the logical OR operator (||
), which also considers falsy values like 0
, false
, or ""
as triggers for the fallback value.
Syntax:
let result = value ?? defaultValue;
Example:
let language = null;
let defaultLang = language ?? "ar_SA"; // result: 'ar_SA'
In this example, language
is null
, so the default 'ar_SA'
is assigned to defaultLang
.
??
?Use the ??
operator when you want to provide a default value only when dealing with null
or undefined
, without mistakenly overriding other falsy values.
?.
)The optional chaining operator (?.
) allows you to safely access deeply nested object properties without worrying about throwing an error if any part of the chain is null
or undefined
.
Syntax:
let result = obj?.property?.subProperty;
Example:
let user = {
name: "John",
address: { city: "New York" },
};
let city = user?.address?.city; // 'New York'
let zip = user?.address?.zipCode; // undefined, but no error thrown
In this example, using ?.
, you can safely attempt to access user.address.city
. If address
were undefined
, the code would simply return undefined
instead of throwing an error.
?.
?The optional chaining operator is particularly useful when working with API responses or complex objects where certain properties may or may not exist, helping avoid runtime errors.