Altcademy - a Forbes magazine logo Best Coding Bootcamp 2023

What are Functions in JavaScript?

If you are learning programming, you may have come across the term "functions" when studying JavaScript or any other programming language. Functions are an essential part of any programming language, and understanding them is crucial to becoming a proficient programmer. In this blog post, we will explain what functions are, how they work, and how to use them in JavaScript. We will also provide code examples and some analogies to help you better understand the concept.

Functions - What are they?

In its simplest form, a function is a piece of reusable code that performs a specific task. You can think of a function like a recipe - a set of instructions that can be followed to achieve a certain outcome. Just like you can use a recipe to make a dish multiple times, you can use a function to perform the same task multiple times in your code.

The main reason we use functions is to avoid repeating code. Repeating code is not only time-consuming but also makes the code harder to maintain and troubleshoot. Functions allow us to write the code once and then reuse it as many times as we need.

JavaScript Functions - A Closer Look

In JavaScript, functions are defined using the function keyword, followed by a function name, a pair of parentheses (), and a pair of curly braces {}. The function name should be a descriptive name that indicates what the function does. The parentheses are used to define any input parameters the function might need, and the curly braces contain the code that will be executed when the function is called.

Here's a simple example of a JavaScript function that adds two numbers together:

function addNumbers(a, b) {
  var sum = a + b;
  return sum;
}

In this example, the function is named addNumbers, and it takes two input parameters: a and b. These are the numbers that will be added together. Inside the curly braces, we have the code that performs the addition and returns the result. The return statement is used to specify the output of the function. When the function is called, the value of the sum variable will be returned as the result.

To use this function in our code, we need to call it. Calling a function is done by using the function name followed by parentheses, with any required input parameters inside the parentheses. Here's an example of how to call the addNumbers function:

var result = addNumbers(5, 3);
console.log(result); // Output: 8

In this example, we are calling the addNumbers function with the arguments 5 and 3. These values will be used as the input parameters a and b inside the function. The function will then perform the addition and return the result, which will be stored in the result variable. Finally, we use console.log() to print the result to the console.

Functions as Building Blocks

One way to think about functions is as building blocks. Just like building blocks can be combined to create larger structures, functions can be combined to create more complex programs. Each function should perform a small, specific task, and then you can use these functions together to create more complex functionality.

For example, let's say we are building a program to calculate the total cost of a shopping cart. We could have a function that calculates the total price of all the items in the cart, another function that calculates the sales tax, and another function that calculates the shipping cost. Then, we could have a final function that combines these values to calculate the total cost. By breaking the problem down into smaller tasks and creating functions for each task, we can make the code easier to understand, maintain, and troubleshoot.

Here's an example of how this might look in JavaScript:

function calculateItemTotal(items) {
  var total = 0;
  for (var i = 0; i < items.length; i++) {
    total += items[i].price * items[i].quantity;
  }
  return total;
}

function calculateSalesTax(total, taxRate) {
  return total * taxRate/100;
}

function calculateShippingCost(total) {
  if (total > 100) {
    return 0;
  } else {
    return 10;
  }
}

function calculateTotalCost(items, taxRate) {
  var itemTotal = calculateItemTotal(items);
  var salesTax = calculateSalesTax(itemTotal, taxRate);
  var shippingCost = calculateShippingCost(itemTotal);
  return itemTotal + salesTax + shippingCost;
}

var items = [
  { price: 20, quantity: 2 },
  { price: 50, quantity: 1 },
];
var taxRate = 10;

var totalCost = calculateTotalCost(items, taxRate);
console.log(totalCost); // Output: 104

In this example, we have four functions: calculateItemTotal, calculateSalesTax, calculateShippingCost, and calculateTotalCost. Each function performs a specific task related to calculating the total cost of the shopping cart. By using these functions together, we can easily calculate the total cost of the cart, including sales tax and shipping.

Conclusion

Functions are an essential part of JavaScript and programming in general. They allow us to write reusable pieces of code that perform specific tasks, making our code more efficient and easier to maintain. By thinking of functions as building blocks that can be combined to create more complex functionality, we can create more organized and modular programs.

Remember that a function in JavaScript is defined using the function keyword, followed by a descriptive name, input parameters in parentheses, and a pair of curly braces containing the code to be executed. Functions can be called using the function name followed by parentheses, with any required input parameters inside the parentheses.

Now that you have a better understanding of functions in JavaScript, you can start using them in your own programs to create more efficient and organized code.