Brilliant
Staff member
- Joined
- Dec 31, 2024
- Messages
- 373
- Reaction score
- 7
- Points
- 18
- User icon
- <svg xmlns="http://www.w3.org/2000/svg" height="14" width="15.75" viewBox="0 0 576 512"><!--!Font Awesome Free 6.7.2 by @fontawesome - https://fontawesome.com License - https://fontawesome.com/license/free Copyright 2025 Fonticons, Inc.--><path fill="#63E6BE" d="M309 106c11.4-7 19-19.7 19-34c0-22.1-17.9-40-40-40s-40 17.9-40 40c0 14.4 7.6 27 19 34L209.7 220.6c-9.1 18.2-32.7 23.4-48.6 10.7L72 160c5-6.7 8-15 8-24c0-22.1-17.9-40-40-40S0 113.9 0 136s17.9 40 40 40c.2 0 .5 0 .7 0L86.4 427.4c5.5 30.4 32 52.6 63 52.6l277.2 0c30.9 0 57.4-22.1 63-52.6L535.3 176c.2 0 .5 0 .7 0c22.1 0 40-17.9 40-40s-17.9-40-40-40s-40 17.9-40 40c0 9 3 17.3 8 24l-89.1 71.3c-15.9 12.7-39.5 7.5-48.6-10.7L309 106z"/></svg>
Handling repeated code blocks efficiently in JavaScript is important for maintainability and performance. If you are encountering repetitive blocks of code, consider these approaches to streamline your code:
---
1. Use Functions
Encapsulate repeated logic in a reusable function. This eliminates duplication and makes it easier to update or modify the behavior in one place.
Example:
Before:
After:
2. Use Loops
If your repeated code involves similar operations on multiple elements, use a loop (e.g., for, forEach, or map) to dynamically bind logic.
Example:
Before:
After:
3. Event Delegation
Instead of attaching event listeners to multiple elements, use event delegation to attach a single listener to a parent element and handle events based on the target.
Example:
Before:
After:
4. Use Higher-Order Functions
For more complex scenarios, use higher-order functions that accept callbacks to encapsulate varying behavior.
Example:
5. Abstract Repeated Code into Classes or Modules
If your logic involves reusable components or repeated behavior across an application, use classes or modules for better scalability.
Example:
6. Template Literals for Repeating HTML
If you’re dynamically generating similar HTML blocks, use template literals for better readability and fewer repetitions.
Example:
Before:
After:
7. Leverage Libraries
If your project allows, use JavaScript libraries like Lodash to simplify repetitive tasks like iterations, filtering, or mapping.
---
By combining these techniques, you can eliminate redundancy, reduce errors, and make your JavaScript code more maintainable.
---
1. Use Functions
Encapsulate repeated logic in a reusable function. This eliminates duplication and makes it easier to update or modify the behavior in one place.
Example:
Before:
JavaScript:
document.getElementById('btn1').addEventListener('click', () => {
console.log('Button 1 clicked');
alert('Action for Button 1');
});
document.getElementById('btn2').addEventListener('click', () => {
console.log('Button 2 clicked');
alert('Action for Button 2');
});
After:
JavaScript:
function handleButtonClick(buttonId, message) {
console.log(`${buttonId} clicked`);
alert(message);
}
document.getElementById('btn1').addEventListener('click', () => handleButtonClick('btn1', 'Action for Button 1'));
document.getElementById('btn2').addEventListener('click', () => handleButtonClick('btn2', 'Action for Button 2'));
---
2. Use Loops
If your repeated code involves similar operations on multiple elements, use a loop (e.g., for, forEach, or map) to dynamically bind logic.
Example:
Before:
JavaScript:
document.getElementById('input1').addEventListener('change', () => console.log('Input 1 changed'));
document.getElementById('input2').addEventListener('change', () => console.log('Input 2 changed'));
document.getElementById('input3').addEventListener('change', () => console.log('Input 3 changed'));
After:
JavaScript:
const inputs = document.querySelectorAll('input');
inputs.forEach((input, index) => {
input.addEventListener('change', () => console.log(`Input ${index + 1} changed`));
});
---
3. Event Delegation
Instead of attaching event listeners to multiple elements, use event delegation to attach a single listener to a parent element and handle events based on the target.
Example:
Before:
JavaScript:
document.getElementById('item1').addEventListener('click', () => console.log('Item 1 clicked'));
document.getElementById('item2').addEventListener('click', () => console.log('Item 2 clicked'));
After:
JavaScript:
document.getElementById('container').addEventListener('click', (event) => {
if (event.target.matches('.item')) {
console.log(`${event.target.id} clicked`);
}
});
---
4. Use Higher-Order Functions
For more complex scenarios, use higher-order functions that accept callbacks to encapsulate varying behavior.
Example:
JavaScript:
function executeOnElements(selector, callback) {
document.querySelectorAll(selector).forEach(callback);
}
executeOnElements('.buttons', (button) => {
button.addEventListener('click', () => {
console.log(`${button.id} clicked`);
});
});
---
5. Abstract Repeated Code into Classes or Modules
If your logic involves reusable components or repeated behavior across an application, use classes or modules for better scalability.
Example:
JavaScript:
class ButtonHandler {
constructor(buttonSelector) {
this.buttons = document.querySelectorAll(buttonSelector);
this.init();
}
init() {
this.buttons.forEach((button) => {
button.addEventListener('click', () => this.handleClick(button));
});
}
handleClick(button) {
console.log(`${button.id} clicked`);
}
}
new ButtonHandler('.buttons');
---
6. Template Literals for Repeating HTML
If you’re dynamically generating similar HTML blocks, use template literals for better readability and fewer repetitions.
Example:
Before:
JavaScript:
document.body.innerHTML += '<div class="item">Item 1</div>';
document.body.innerHTML += '<div class="item">Item 2</div>';
document.body.innerHTML += '<div class="item">Item 3</div>';
After:
JavaScript:
const items = [1, 2, 3];
document.body.innerHTML += items.map((i) => `<div class="item">Item ${i}</div>`).join('');
---
7. Leverage Libraries
If your project allows, use JavaScript libraries like Lodash to simplify repetitive tasks like iterations, filtering, or mapping.
---
By combining these techniques, you can eliminate redundancy, reduce errors, and make your JavaScript code more maintainable.