Week 3 - Functions and strings

Functions

String functions

JavaScript Modules

Scope

IDE navigation

DRY (Don’t Repeat Yourself)

Function size

Using LLMs for efficient learning

Practice

Assignment

Back to core program

What is DRY?

DRY stands for "Don't Repeat Yourself". It's a fundamental principle in programming that encourages you to avoid writing the same code multiple times. Instead, you should write code once and reuse it wherever needed. Using the DRY principle has a few huge advantages:

<aside> 💡

The main idea is simple: if you find yourself copying and pasting code, there's probably a better way to organise it.

</aside>

Simple Examples

❌ Not Following DRY (Repetitive Code)

// Calculating areas and perimeters without functions
const rectangle1Width = 5;
let rectangle1Height = 10;
let rectangle1Area = calculateArea(rectangle1Width, rectangle1Height);
console.log("Rectangle 1 area:", rectangle1Area);

let rectangle2Width = 8;
let rectangle2Height = 12;
let rectangle2Area = rectangle2Width * rectangle2Height;
console.log("Rectangle 2 area:", rectangle2Area);

let rectangle3Width = 3;
let rectangle3Height = 7;
let rectangle3Area = rectangle3Width * rectangle3Height;
console.log("Rectangle 3 area:", rectangle3Area);

Notice how we're repeating the same calculation (width * height) three times. If we realise we need to change how we calculate area, we'd have to update it in three places!

✅ Following DRY (Using a Function)

// Calculating areas with a reusable function
function calculateRectangleArea(width, height) {
  return width * height;
}

let rectangle1Area = calculateRectangleArea(5, 10);
console.log("Rectangle 1 area:", rectangle1Area);

let rectangle2Area = calculateRectangleArea(8, 12);
console.log("Rectangle 2 area:", rectangle2Area);

let rectangle3Area = calculateRectangleArea(3, 7);
console.log("Rectangle 3 area:", rectangle3Area);

Much better! The calculation logic is in one place. If we need to change it, we only update the function.

Another Example: Greeting Users

❌ Without DRY:

console.log("Hello, Alice! Welcome to our website.");
console.log("Hello, Bob! Welcome to our website.");
console.log("Hello, Charlie! Welcome to our website.");

✅ With DRY:

function greetUser(name) {
  console.log(`Hello, ${name}! Welcome to our website.`);
}

greetUser("Alice");
greetUser("Bob");
greetUser("Charlie");

Now if we want to change the greeting message (for example, change "website" to "app"), we only need to change it once in the function!


The HackYourFuture curriculum is licensed under CC BY-NC-SA 4.0 **

CC BY-NC-SA 4.0 Icons

*https://hackyourfuture.net/*