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.
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
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);
Removing Duplicates with Set :
For an array with duplicate values you can remove duplicate value using set
Example :
const letter= ["a", "b", "c" , "c" , "a" , "d" ,"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(obj1)); // true console.log(weakset.has(obj2)); // true // Attempting to add the same object again weakset.add(obj1); // obj1 is already present, won't be added again console.log(weakset.has(obj1)); // true console.log(weakset.has(obj2)); // true // Removing an object from the WeakSet weakset.delete(obj1); console.log(weakset.has(obj1)); // false // Adding the object again weakset.add(obj1); console.log(weakset.has(obj1)); // true
In this article, we explored some important concepts that can help prevent errors when accessing values that might be undefined or null, as well as methods for managing data more effectively when necessary.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3