Core Premise of Function in JavaScript
Source: Dev.to
Is this a function in JavaScript?
function fiveSquared() {
return 5 * 5;
}
Technically, yes. However, fiveSquared lacks the reusability that a real‑world function should provide. No matter how many times you call fiveSquared(), it will always return 25. If you need to calculate the square of 6, you’d have to write a new function (sixSquared). This repeats the same logic and violates the DRY (Don’t Repeat Yourself) principle.
The Cure for the “Pain of the Century”
We fix this by using parameters—placeholders for input values—so the same function can work with any number.
function calculateSquare(num) {
return num * num;
}
Now the function can be reused:
calculateSquare(5)returns 25calculateSquare(6)returns 36calculateSquare(100)returns 10,000
The logic is written once and can be invoked with any argument, keeping your code DRY and scalable.
Final Conclusion
Writing functions is a fundamental step in becoming an efficient developer. A good function provides flexible logic that can be reused without rewriting code. By using parameters instead of hard‑coded values, you avoid repetitive work and keep your code clean.
Test Your Knowledge: The Function Challenge!
- Write a function called
multiplyByTenthat takes one parameter and returns that number multiplied by 10. - What happens if you create a function with a parameter but never use that parameter inside the logic? Does it still follow the DRY principle?
- Write a function that takes two parameters (e.g.,
num1andnum2) and returns their sum.
What Is Next?
In this article we learned how parameters let us pass different data into a function, making the code reusable.
Next, we’ll explore how to make the operation itself a placeholder. By passing a function as an argument, we can create Higher‑Order Functions (HOFs) that can perform multiplication, addition, or any other operation without changing the core logic. Get ready to make your code as flexible as your data!