DEV Community

Cover image for JavaScript Functions Dumbed down

Posted on

JavaScript Functions Dumbed down

What the hell is a function?

Well, a function is a reusable code (which means you can call it to use at different places in your project). I know you're probably wondering what nonsense I'm talking about, but hold on I'll explain better.

We all have trash cans at our homes, correct? Now, what do we use those trash cans for? We obviously throw our waste in it (i.e biscuit wrappers, nylons, etc...). Do these trash cans have a fixed place that they can never be moved from? The trash cans can obviously be moved to different places, correct?

Now, when you move the trash can to a different place, does it change from a trash can to a box? The answer is obviously not. So what's the difference? The difference is the contents in the trash can, because you can move the trash can anywhere in the world, but it's still a trash can, and we can empty the contents each day so that we can use it again.

This is exactly what functions do in JavaScript. Take the following codes as an example:

Let's say you created a function to get someone's favourite colour

function favouriteColour(colour) {
  const userFavouriteColour = colour;
  return console.log(`The user's favourite colour is ${userFavouriteColour}`)
Enter fullscreen mode Exit fullscreen mode

Now, we can see in the function above gets the user's colour by passing it as a parameter [the value between the parenthesis function(colour)] and returns the text that tells you the user's favourite colour return console.log(). We finally call the function and pass a colour to it as an argument favouriteColour("blue").

Let's take this function and try to call it (or use it) somewhere else. Take for example we have a second user and we have a second user and we want to get their favourite colour using the function we've created. The code below shows how this will work without changing the initial function itself.

function secondUser() {
Enter fullscreen mode Exit fullscreen mode

You'll notice in this new code, we the function we declared earlier, and only changed the argument from blue to pink. If you run the code, you'll notice that it shows the text, with this new user's favourite colour.

What magic happened here? Well, if you recall the example of the trash can, you'll understand that just as we can move the trash can and it still remains a trash can and carries out the function of a trash can. This function works the same way, in the sense that we are using it somewhere else, the only difference is the content (colour). It stills carries out the role of printing out the user's favourite colour.

I hope this gives you a better understanding of functions and how they work. I know this one's a bit lengthy, but I wanted to go a bit deeper to explain the concept with real world and code examples. Till next time....


Top comments (0)