Keeping your code DRY
august-jk
Posted on June 22, 2022
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;
}
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;
}
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)
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)
That looks great!
.map() has to be one of my favorite built in JavaScript methods, and now you know why!
Posted on June 22, 2022
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
November 30, 2024