What is Hard Coding and Why We Should Avoid It
Hard coding means putting specific numbers or values directly into your code instead of using variables, constants, or getting them from outside sources.
This makes the code less flexible because if you need to change those numbers, you have to go into the code and update them everywhere they are used.
Let me illustrate this with a simple example. Suppose you're creating a shopping cart system that applies a constant discount to the total price:
function calculateTotalPrice(items) { let totalPrice = 0; for (let i = 0; i < items.length; i++) { totalPrice += items[i].price; } // Hardcoded discount applied at multiple places const discount = 0.1; // 10% discount totalPrice -= totalPrice * discount; // Applying discount here return totalPrice; } function displayFinalPrice(items) { let totalPrice = 0; for (let i = 0; i < items.length; i++) { totalPrice += items[i].price; } // Hardcoded discount applied again const discount = 0.1; // 10% discount totalPrice -= totalPrice * discount; // Applying discount here console.log("Final Price: $" + totalPrice.toFixed(2)); }
In this example, the discount rate (0.10
) is hardcoded in two places: calculateTotalPrice
and displayFinalPrice
. If you need to change the discount to 0.15
, you would have to update it in both locations. If you forget to update one, your application might behave inconsistently.
A better approach is to define such values as constants or variables. Here’s how you can refactor the code:
const DISCOUNT_RATE = 0.1; // 10% discount function calculateTotalPrice(items) { let totalPrice = 0; for (let i = 0; i < items.length; i++) { totalPrice += items[i].price; } // Using the constant for discount totalPrice -= totalPrice * DISCOUNT_RATE; return totalPrice; } function displayFinalPrice(items) { let totalPrice = 0; for (let i = 0; i < items.length; i++) { totalPrice += items[i].price; } // Using the constant for discount totalPrice -= totalPrice * DISCOUNT_RATE; console.log("Final Price: $" + totalPrice.toFixed(2)); }
By using a constant like DISCOUNT_RATE
, you only need to update the discount rate in one place. This approach ensures that all parts of your code use the same value, preventing inconsistencies.
Additionally, using descriptive names for constants, like DISCOUNT_RATE
, enhances code readability and makes it clear what the value represents.
Avoiding hardcoded values and using well-named variables or constants will make your code more flexible, readable, and less error-prone.
Get my free, weekly JavaScript tutorials
Want to improve your JavaScript fluency?
Every week, I send a new full-length JavaScript article to thousands of developers. Learn about asynchronous programming, closures, and best practices — as well as general tips for software engineers.
Join today, and level up your JavaScript every Sunday!
Thank you, Taha, for your amazing newsletter. I’m really benefiting from the valuable insights and tips you share.