In this article, we will explore how to prevent errors when trying to access data that might be undefined or null, and we’ll look at methods you can use to manage data effectively when necessary.
Safe Access with Optional Chaining
In JavaScript, when trying to access a value or function within nested objects, if the result is undefined, your code may throw an error. This error can stop the execution of your code. However, if you use the optional chaining operator, it will return undefined instead of throwing an error if the value or function does not exist. This prevents your code from crashing.
Example :
const person = {
name: 'John',
address: {
city: 'New York'
}
};
console.log(person.address?.city); // 'New York'
console.log(person.address?.country); // undefined, no error
Nullish Coalescing
If the value of a variable is null or undefined,To avoid this, you can use the nullish coalescing operator
Example :
function getconfig(config) {
return config ?? { timeout: 1000, retries: 3 };
}
let userConfig = null;
let finalConfig = getConfig(userConfig); // { timeout: 1000, retries: 3 }
console.log(finalConfig);
Managing Duplicates with Set and WeakSet
Removing Duplicates with Set :
For an array with duplicate values you can remove duplicate value using set
Example :
const letter= ["a","c", "b", "d" , "c" , "a" ,"d" ];
const result= [...new Set(letter)];
console.log(result) => ["a", "b" , "c" , "d"]
Preventing Duplicates with WeakSet :
Since WeakSet holds references to objects, an object can only be added to a WeakSet once.
Example :
// Creating a WeakSet
const weakset = new WeakSet();
// Defining objects
const personJane = { name: 'jane' };
const personMike = { name: 'mike' };
// Adding objects to the WeakSet
weakset.add(personJane);
weakset.add(personMike);
console.log(weakset.has(personJane)); // true
console.log(weakset.has(personMike)); // true
// Attempting to add the same object again
weakset.add(personJane); // personJane is already present, won't be added again
console.log(weakset.has(personJane)); // true
console.log(weakset.has(personMike)); // true
// Removing an object from the WeakSet
weakset.delete(personJane);
console.log(weakset.has(personJane)); // false
// Adding the object again
weakset.add(personJane);
console.log(weakset.has(personJane)); // true
Top comments (4)
Optional Chaining is so basic but very useful. Or use TypeScript.
I totally agree! Optional Chaining greatly simplifies the readability and debugging process of code, especially when managing large and complex data structures.
The above code has a bug. obj1 and obj2 are actually personJane and personMike
I am sorry. I must have missed it. I update it immediately