READ TIME - 2 MINUTES
Today, we’ll cover 2 key practices to make your JavaScript functions simpler and easier to use: limit function arguments and ensure each function does only one thing.
These practices make your code easier to read and maintain. They help your functions stay predictable, so you can avoid issues and save time on debugging or refactoring.
Many developers skip these practices to deliver code fast, but this can lead to code that’s messy and hard to work with as your app grows.
Limiting function arguments and focusing functions on one job are core to clean code.
Following these practices makes your code clearer and easier for others to understand.
Give each function a single purpose.
Aim for 2 or fewer arguments in a function.
Use objects and destructuring if you need more inputs.
Break down complex functions to make code more modular and testable.
Limiting Function Arguments (Two or Fewer)
Using many parameters in a function adds complexity.
If you need more than 2 arguments, try putting them in an object and using destructuring.
Bad example
This example is hard to read without checking the function.
Good example
With destructuring, you can immediately see what each property is and how to use the function.
This approach helps avoid mistakes since each property has a clear label.
Functions Should Do Only One Thing
A function with multiple tasks is harder to read and reuse.
Each function should do one thing, so you can follow it more easily and use it in other places.
Bad example
In this example, manageInventory
is handling both ordering and saving products, which makes it harder to test.
Good example
Now, each function has one job: reorderLowStock
checks for low stock, saveAllProducts
saves products, and isLowStock
determines if stock is low. This setup is easier to read and maintain.
Conclusion
Limiting function arguments and following the “one job” rule improves the clarity and quality of your JavaScript.
These simple practices make your functions modular, readable, and easier to maintain over time.
Use these tips to write great JavaScript in your projects!
See you next Saturday!
Keep up the great work! :)
Clean code = easy to change 🤘
Great article, Edi!