I used to write 6 lines for something that needed just one.
Refactor your code like this :
As devs, we often face the same problem:
checking if an element exists in an array.
Let’s say you’re building a shopping cart 🛒and you want to check if a specific item is already inside.
Here’s how I used to do it 👇
let cart = ["Laptop", "Mouse", "Keyboard", "Monitor", "Webcam", "USB Hub",
"External Hard Drive", "Desk Lamp", "Office Chair", "Notebook", "Pen", "Headphones", "Microphone", "Smartphone", "Charger", "Tablet", "Printer", "Router", "HDMI Cable", "Mouse Pad", "Power Bank", "Flash Drive", "Graphic Tablet"];
let found = false;
for (let item of cart) {
if (item === "Laptop") {
found = true;
}
}
console.log(found); // true
It works. ✅
But it’s long, repetitive, and harder to maintain.
Then I discovered this one-liner 👇
let found = cart.includes("Laptop");
console.log(found); // true
Same output.
Same time complexity.
Same space complexity.
But way more readable and maintainable.
📊 Code Complexity Comparison
Both versions have the same time and space complexity —
O(n) and O(1) respectively.
But .includes() wins where it really matters:
✅ Lower cyclomatic complexity (1 vs 2)
✅ Cleaner and easier to read
✅ Far more maintainable
💬 The Lesson as Junior Dev:
Clean code isn’t just about making it work : it’s about making it simpler, clearer, and easier to maintain.
Fewer lines, same power.
That’s what clean code looks like. ✨
Follow for more Tipps!
Senior Android Engineer @ Bragi
3wcomposed { } has been discouraged for usage and soon deprecated.