1 - Optimizing Parameter Checks
❌ Stop this:
if (userRole !== 'admin' && userRole !== 'moderator' && userRole !== 'user') {
console.error("Invalid user role")
}
✅ Use instead:
const allowedRoles = ['admin', 'moderator', 'user'];
if (!allowedRoles.includes(userRole)) {
console.error('Invalid user role');
}
2 - useReducer for toggle states
❌ Stop this:
const [isModalVisible, setIsModalVisible] = useState(false)
setIsModalVisible((prevState) => !prevState)
✅ Use instead:
const [isModalVisible, toggleModalVisibility] = useReducer((currentValue) => !currentValue, false)
toggleModalVisibility()
3 - Destructured Objects as Parameters
❌ Stop this:
const processUserData = (firstName, lastName, age, email) => {
....
}
processUserData("Frank", "James", 35, "fjames@gmail.com");
✅ Use instead:
const processUserData = ({ firstName, lastName, age, email }) => {
....
}
processUserData({
firstName: "Frank",
lastName: "James",
age: 35,
email: "fjames@gmail.com"
});
4 - Efficient Object Cloning
❌ Stop this:
const originalObject = {
key1: 'value of key1',
key2: {
key2a: () => console.log('function value of key2a')
}
}
const objectCopy = originalObject
✅ Use instead:
const originalObject = {
key1: 'value of key1',
key2: {
key2a: () => console.log('function value of key2a')
}
}
const objectCopy = structuredClone(originalObject)
// or
const objectCopy = {...originalObject}
5 - Use Set to efficiently manage unique values
❌ Stop this:
const uniqueItemsArray = ['Apple', 'Banana', 'Orange', 'Banana', 'Apple'];
// Adding new items to the Array
uniqueItemsArray.push('Grapes');
uniqueItemsArray.push('Orange'); // Already exists but added again
// Checking if a value exists in the Array
const hasGrapes = uniqueItemsArray.includes('Grapes');
// Deleting an item from the Array
uniqueItemsArray = uniqueItemsArray.filter(item => item !== 'Banana');
uniqueItemsArray.forEach(item => {
console.log(item);
});
✅ Use instead:
const uniqueItemsSet = new Set(['Apple', 'Banana', 'Orange', 'Banana', 'Apple']);
// will show ['Apple', 'Banana', 'Orange']
// Adding new unique items to the Set
uniqueItemsSet.add('Grapes');
uniqueItemsSet.add('Orange');
// Checking if a value exists in the Set
const hasGrapes = uniqueItemsSet.has('Grapes');
// Deleting an item from the Set
uniqueItemsSet.delete('Banana');
// Iterating through the Set
for (let item of uniqueItemsSet) {
console.log(item);
}