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

Why reduce function size?

Writing smaller, focused functions is a fundamental principle of clean code. Functions should do one thing and do it well and following this principle has the following advantages:

Let’s look at an example. Have a look at this code:

function processUserData(user) {
  // Validate user
  if (!user.name || user.name.length < 2) {
    console.error("Invalid name");
    return null;
  }
  if (!user.email || !user.email.includes("@")) {
    console.error("Invalid email");
    return null;
  }
  
  // Format user data
  const formattedName = user.name.trim().toLowerCase();
  const formattedEmail = user.email.trim().toLowerCase();
  
  // Calculate age from birthdate
  const today = new Date();
  const birthDate = new Date(user.birthdate);
  let age = today.getFullYear() - birthDate.getFullYear();
  const monthDiff = today.getMonth() - birthDate.getMonth();
  if (monthDiff < 0 || (monthDiff === 0 && today.getDate() < birthDate.getDate())) {
    age--;
  }
  
  // Create user profile
  const profile = {
    name: formattedName,
    email: formattedEmail,
    age: age,
    isAdult: age >= 18
  };
  
  // Save to database
  console.log("Saving user profile...");
  // database.save(profile);
  
  return profile;
}

This function does too many things: it validates information, formats it, has an age calculation, and database operations. No other part of the code can use this function now meaning someone that wants to do something similar will need to rewrite it. Now let’s look at a good approach:

function validateName(name) {
  return name && name.length >= 2;
}

function validateEmail(email) {
  return email && email.includes("@");
}

function formatString(str) {
  return str.trim().toLowerCase();
}

function calculateAge(birthdate) {
  const today = new Date();
  const birthDate = new Date(birthdate);
  let age = today.getFullYear() - birthDate.getFullYear();
  const monthDiff = today.getMonth() - birthDate.getMonth();
  
  if (monthDiff < 0 || (monthDiff === 0 && today.getDate() < birthDate.getDate())) {
    age--;
  }
  
  return age;
}

function createUserProfile(user) {
  const age = calculateAge(user.birthdate);
  
  return {
    name: formatString(user.name),
    email: formatString(user.email),
    age: age,
    isAdult: age >= 18
  };
}

function processUserData(user) {
  // Validate
  if (!validateName(user.name)) {
    console.error("Invalid name");
    return null;
  }
  
  if (!validateEmail(user.email)) {
    console.error("Invalid email");
    return null;
  }
  
  // Process
  const profile = createUserProfile(user);
  
  // Save
  console.log("Saving user profile...");
  // database.save(profile);
  
  return profile;
}

Now each function has a single, clear responsibility. The code is easier to read and reuse, if someone else wants to validate an email there is now a function to do that already.

<aside> 💡

If a function is longer than 20-30 lines or does multiple things, consider breaking it down. Look for natural separation points where you can extract helper functions. Your future self (and your teammates) will thank you!

</aside>


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

CC BY-NC-SA 4.0 Icons

*https://hackyourfuture.net/*