DEV Community

Nic
Nic

Posted on

Why use functions?

You could write your whole JavaScript script in one long thing. The advantage of is that you read it from top to bottom. And if you only have a few lines of code, that isn't going to be a problem. But if you have 400 lines of code, then it gets tricky (as I found out the hard way).

There are two main reasons to use functions in JavaScript (and probably other languages too, but JS is the one I'm familiar with).

1. So you don't repeat yourself

You may have come across the DRY, for don't repeat yourself. If you find you need to write the same block of code twice, it would be better to put it in a function. That way you've only written it once.

You might say "I'm not writing it twice, I'm copying and pasting it", but that's just semantics. Also, if you change something in that code, you have to remember to change it in both places. Maybe it's something you can easily find and replace, but maybe it's not.

It's all about cutting down the amount of work you have to do. And the number of places you might have errors.

2. To make it readable

Let's say your script has 400 lines of code. You don't look at it for a year, but when you come back you have to make a change. Good luck finding it! You might have to read through all the lines and figure out what they're doing. Maybe you've written good comments explaining what each bit does. But you could have replaced some of those comments with functions.

If you're reading through your code and you have this:

getHighScore();
displayHighScore();
playGame();
calculateHighScore();
setNewHighScore();
Enter fullscreen mode Exit fullscreen mode

you can guess what's going on in each of those functions without having to read all the lines within them. If each of those functions contained 10 lines of code, you've just saved yourself from having to read 45 lines of code.

In conclusion: write functions.

Top comments (0)