Codementor Events

Javascript functions and why do we need them?

Published Sep 02, 2021Last updated Feb 28, 2022
Javascript functions and why do we need them?

This article demystifies an idea of programming functions. Also, we'll talk about functions in Javascript.

Why do we need functions?

Have you needed to calculate something? For example, how much money do you need to buy 10 apples. It's easy, right? We know that one apple costs $1(not a real price). Multiply 1 by 10 and we'll get $10. But usually, people sell apples by weight. E.g. $1.24 per 1 kg.

What to do if we need 2.7 kilograms of apples to bake a fruit pie? In this case, we usually take our calculator to compute $1.24 x 2.7 kg. This is a simple task, Sergiy! How does it relate to programming functions?

Imagine you need to do such calculations often. You have a business of baking apple pies. You get 5 orders a day, on average. And you also need to calculate how much money you need for other ingredients. Can we automate the process?

You know you need:

  • 0.3 kg of butter
  • 0.08 kg of flour
  • 0.115 kg of sugar
  • 2.7 kg of apples

"But we can calculate it one time and use the result in the future!" - you might say. And it's a valid point. What if we may get other orders? Not only pies even, but all kinds of food. And what if the price for some product changes? We'd need to do the calculations once again.

Flying to the Moon

Let's imagine another example.

Assume we live in a world where everyone can travel in space. You also have a spaceship. You decided to fly to the Moon this weekend. You sit in the spaceship. There are controls to move in various directions. For this, you need to manually control the engines, like in a car.

You don't know how much fuel you need because you don't know what path you should fly. There are 3 possible paths. The one, where you fly directly to the Moon, seems to be the most proper. Well, there are 2 points, we fly from the first to the second, right?

You recall both Moon and Earth are moving. The task becomes complicated. We're lucky because people already invented math and physics. All we need is to get some formulas to calculate the path and how much fuel you need. You see the formulas, start the calculations, and understand it isn't so straightforward. You may spend a month on the calculations alone and still get the wrong results!

You're lucky because there are people who flew to the Moon already. So they shared the calculations. You see that you need to begin the travel at a specific time and location. Then, you:

  • accelerate the engines to the first cosmic velocity
  • get to the Earth's orbit
  • fly some time to a specific moment and ...
  • accelerate the engines to the second cosmic velocity
  • adjust your path to fly to the Moon
  • extra steps to land on the Moon

It seems like a plan! There are many problems though. Even if you have many sensors, it's difficult to control the ship manually: directing it in the right directions and increasing/decreasing the power of the engine. Even if you have friends with you who help, it's still difficult.

  • What if you miss the moment when you should accelerate? Or you turned a bit, right? Left? Didn't start at a time?
  • What if you miss another cosmic object moving near you? What if you should change your path a bit due to it? You'll need to do a lot of calculations. Which is quite hard(more like impossible in the flying spaceship, has a limited amount of fuel).
  • How would you land on the surface? There is likely to be full darkness.
  • There are many other possible situations that amend the plan.

Automated spaceships

A lot of people fly on them, not on the manual ones like you own. With one, you can sit and just fly looking in space. Thinking about what you'll do on the Moon. What changed?

Such spaceships have software, which does the calculations. Software? Yes, programs written by software engineers. How does it help? It can re-calculate the path if you're late on time. Or, decided to fly to a store first. The program can react to new data such as changes in the spaceship's weight when you met a friend in the store and picked him up.

The program has the formulas, it only needs inputs to make new calculations, if needed. It's better because we don't need to control the travel and re-do computations when something changes. Decided to fly back because you forgot an e-book? No problem, here's our new path, if you want to see it. Anyway, the scapeship will fly automatically.

What are functions?

Have you noticed a pattern in these two examples? We need to re-do the calculations if something changes. This "something" is what we include in the formulas as a variable. A variable, because it can vary. Sometimes we need to compute a thing fast. For example, when a spaceship's weight changed. We should rectify a path quickly, otherwise, we lose more fuel.

There is a real-world example too. To pay taxes, you calculate your monthly income and subtract, say, 16% of it. Doing this once a month is acceptable to do on a calculator, okay. What if you need to report your business income and calculate the tax every day? Doing this once a day also seems to be okay for you. Imagine, you have 20 businesses. It becomes routine. We know a formula, let's automate the calculation!

If you don't understand the code below, there are explanations in the next section.

function calculateTax (income) {
  return income * 0.16;
}

You do the same thing, but programmatically. The difference is that this can be automated more and more. A function takes some input, transforms it, and returns the new output. In the top example(see the picture below) the function doesn't do any transformation, it returns the same output.

In the bottom example, it returns not the same input. It did calculations and return only a part of it! It's because we apply an algorithm there to do some useful work. Algorithm? A sequence of steps to do. In our case, it was multiplying a number with 0.16(16%) to get a tax. There are more complicated algorithms. Waking up, going for a walk are also algorithms because it's a sequence of some instructions. Yes, they are complex inside. To walk you need to put your feet in the right places at the right time, leveraging your weight. Sleeping? A lot of processes to solidify the information you collected through the day, updating body cells, etc.

When you read this article, many processes are going on. A browser waits until you scroll down to calculate the necessary length of the page to be scrolled. When you scroll, it re-draw the text and media to put them in the right position. Many things are automated programmatically.

Javascript functions

So, we need functions to take inputs and transform them to produce some result. Let's get familiar with the syntax for functions in JS:

// a keyword to indicate you make a function
// | the name of it
// | | arguments(i.e. inputs)
// | | |
function calculateTax (income) {
  return income * 0.16;
} // | | | - 0.16 is our 16% we wanna multiply to
// | | multiply
// | the input we pass to the function
// a keyword to specify you want to return a result

// - is a comment

Why do we need a name for a function? We'll call it somewhere else when needed.

// note: you need to declare this function first as you saw above
const myTax = calculateTax(100);
// now, "myTax" contains 16 (100 * 0.16)

To call a declared function, you should write its name and add parentheses: calculateTax(). In parentheses, you should specify the arguments the function requires. As you now know, a function takes some input to do calculations and produces a modified input - a transformation. That's why we put our income there: calculateTax(100).

A function can accept various amounts of inputs.

function calculateTax (income, tax) {
  return income * tax;
}

const myTax = calculateTax(100, 0.16);

In case, we need flexibility, I specified a second input - tax. Thus, we have 2 inputs(arguments) that the function takes and can manipulate with.

Why do write functions if we can just put the code directly(imperatively)?

Yes, we may.

const tax = 100 * 0.16;

But the income and tax are static variables, they don't change. Hardcoded. What if we have a different income number? Well, we could evaluate income from some input.

// it's a pseudocode. Imagine we retrieve income somewhere
// e.g. from a terminal input, or, from some field on a website, etc.
const income = getIncomeFromIncome();

const tax = income * 0.16;

The idea remains unchanged. Why do we need functions then? What if you need to re-use this logic somewhere else? In 2, 5, 100 places? Writing the same code isn't a good idea because you should modify all of it. If you have one place where the logic lays, you can change just it.

What "return" does? I mean, why do we need to return a result?

How do we know what a function produces?

function sum (a, b) {
  a + b;
}

const result = sum(5, 10); // "result" is undefined

Why result there is undefined? We made the calculation, right? We did, but we didn't return anything. The function doesn't produce a result. If a function doesn't return something explicitly, the result of its execution(call) is undefined.

We need functions to make some useful work. To transform input and produce an output. Do calculations that can be automated. I didn't cover all the Javascript function tricks but tried to explain why do we need functions at all. To provide a general idea.

Follow me on Twitter for other useful stuff.

Discover and read more posts from Serhii C.
get started
post commentsBe the first to share your opinion
Show more replies