DEV Community

august-jk
august-jk

Posted on

Keeping your code DRY

Hello World!

Welcome to my first ever blog post!

I thought I would start with something that took me some time to get used to:

  • Keeping your code DRY.

DRY stands for Don't Repeat Yourself, which I have a hard time with in my day-to-day interactions, so you can imagine how writing DRY code could be quite foreign to me!

How do you write DRY code?

Well, let's first look at some WET (Write Everything Twice) code.

Let's say you're iterating over an array:
let array = [1, 3, 6, 9]
We want to increase each number in the array by 1, so our result would be:
[2, 4, 7, 10]
Here's what that would look like:

function increaseByOne(array) {
  for(let i = 0; i < array.length; i ++) {
    array[i] += 1
    }
  return array;
}
Enter fullscreen mode Exit fullscreen mode

This looks like a nice snippet of code, right?

And it definitely gives us the output we're looking for!

Well, if you really look at it, a few things could be improved!
First of all, we can only use this to add 1 to each number in the array.
What if we wanted to subtract 1? Or multiply by 2?
We would have to write an entirely new function and it would definitely be WET:

Let's take a look at how we would write a function to multiply by 2 in the same way:

function multiplyByTwo(array) {
  for(let i = 0; i < array.length; i ++) {
    array[i] *= 2
    }
  return array;
}
Enter fullscreen mode Exit fullscreen mode

That's almost identical and yet we're still repeating ourselves!

How can we make this more straightforward and easier to read as well as making the code itself a little more diverse?

One of my favorite built in JavaScript methods is .map()

.map() tells your code to iterate over an array, then it takes a callback function to do whatever it is you need to do with that array!

And the best part is, it's non-destructive so we can avoid any bugs.

Let's rewrite that first function and use .map() instead:

function increaseByOne(x) {
return x + 1;
}
array.map(plusOne)
Enter fullscreen mode Exit fullscreen mode

Wow! It's that easy?

It definitely is, and doesn't that look a whole lot cleaner too?

Now let's replicate the second function:

function multiplyByTwo(x) {
return x * 2;
}
array.map(multiplyByTwo)
Enter fullscreen mode Exit fullscreen mode

That looks great!

.map() has to be one of my favorite built in JavaScript methods, and now you know why!

Top comments (0)