Javascript Features You Need to Know

Sonay Kara - Oct 2 - - Dev Community

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, when trying to access a value or function within an object, 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

Enter fullscreen mode Exit fullscreen mode

Nullish Coalescing

If a variable’s value is null or undefined, it can break your code. To assign a default value when a variable is null or undefined,** 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);

Enter fullscreen mode Exit fullscreen mode

Managing Duplicates with Set and WeakSet

Removing Duplicates with Set:

If an array contains duplicate values, you can remove those duplicates by using Set. Here's how to use this structure:

const numbers = [1, 2, 3, 4, 4, 5, 6, 6, 7, 8, 9, 9];
const uniqueNumbers = [...new Set(numbers)];

console.log(uniqueNumbers); // [1, 2, 3, 4, 5, 6, 7, 8, 9]

Enter fullscreen mode Exit fullscreen mode

Preventing Duplicates with WeakSet:

Since WeakSet holds references to objects, an object can only be added to a WeakSet once. Here's an example:

// Creating a WeakSet
const weakset = new WeakSet();

// Defining objects
const obj1 = { name: 'Alice' };
const obj2 = { name: 'Bob' };

// Adding objects to the WeakSet
weakset.add(obj1);
weakset.add(obj2);

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

Enter fullscreen mode Exit fullscreen mode

Conclusion

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.

. . . . . . .
Terabox Video Player