Altcademy - a Forbes magazine logo Best Coding Bootcamp 2023

How To Write A Function In JavaScript

In this blog post, we will be exploring how to write a function in JavaScript. Functions are a fundamental concept in programming, and as someone who is learning programming, it is essential to understand how they work and how to create them. We will start by explaining what a function is and then dive into some examples to help you understand how to create and use them in your JavaScript code.

What is a Function?

A function is a reusable block of code that can be called multiple times to perform a specific task. Functions can be thought of as a machine that takes some input, performs a certain action, and then produces an output. In programming, these "machines" can be called multiple times, allowing us to avoid repeating the same code over and over again.

Imagine you have a recipe to make a sandwich. Instead of writing out the steps to make a sandwich every time you want to make one, you can simply refer to the recipe. Functions work in a similar way, allowing you to write the code once and then reference it when needed.

Creating a Function

In JavaScript, there are several ways to create a function. The most common way is using the function keyword, followed by the name of the function, a pair of parentheses, and then a pair of curly braces {}. The code inside the curly braces is the body of the function and is executed when the function is called.

Here's an example of a simple function that takes no input and outputs the message "Hello, World!" to the console:

function sayHello() {
  console.log("Hello, World!");
}

In this example, the function is called sayHello, and its body contains a single line of code that uses the built-in console.log() function to print the message "Hello, World!".

Calling a Function

To call a function, simply write the name of the function followed by a pair of parentheses (). This tells JavaScript to execute the code inside the function. Here's how we can call the sayHello function:

sayHello(); // Output: Hello, World!

When this line of code is executed, it will call the sayHello function, which in turn will print "Hello, World!" to the console.

Functions with Parameters

Functions can also accept input, which is known as a parameter. Parameters are variables that can be passed into a function when it is called. They are defined inside the parentheses when creating the function. A function can have multiple parameters, separated by commas.

Here's an example of a function that accepts two parameters, a and b, and returns their sum:

function add(a, b) {
  return a + b;
}

When calling a function with parameters, simply pass the values you want to use as input inside the parentheses. In this example, we can call the add function with two numbers:

add(3, 4); // Output: 7

In this case, the add function will take the values 3 and 4, add them together, and return the result, which is 7.

Return Values

As you saw in the previous example, a function can return a value using the return keyword. The return keyword is followed by the value or expression that should be returned when the function is called. Once a return statement is reached, the function stops executing and the value is returned to the caller.

Here's an example of a function that takes a number as input and returns its square:

function square(x) {
  return x * x;
}

We can call this function and store the result in a variable:

var result = square(5);
console.log(result); // Output: 25

In this example, the square function takes the value 5, multiplies it by itself, and returns the result (25). This value is then stored in the result variable and printed to the console.

Anonymous Functions and Arrow Functions

JavaScript also supports anonymous functions, which are functions without a name. Anonymous functions are often used as arguments for other functions or as a one-time-use function.

Here's an example of an anonymous function that is passed as an argument to the built-in setTimeout function:

setTimeout(function() {
  console.log("This message will appear after 3 seconds");
}, 3000);

In this example, the anonymous function is created using the function keyword without a name, followed by the function body. The setTimeout function takes two arguments: a function to execute and the number of milliseconds to wait before executing it. In this case, the anonymous function will be executed after 3,000 milliseconds (3 seconds).

JavaScript also provides a shorter syntax for creating anonymous functions called arrow functions. An arrow function is created using the => operator, which is placed between the function's parameters and its body. Here's the previous example, rewritten using an arrow function:

setTimeout(() => {
  console.log("This message will appear after 3 seconds");
}, 3000);

In this example, the anonymous function is created using the => operator instead of the function keyword. The result is the same: the message will be printed to the console after 3 seconds.

Conclusion

Functions are an essential concept in programming, allowing you to create reusable blocks of code that can be called multiple times to perform a specific task. In this blog post, we have covered the basics of creating and using functions in JavaScript, including defining functions with the function keyword, calling functions, using parameters and return values, and working with anonymous and arrow functions.

As you continue learning programming, you will encounter functions in many different contexts and use them to create more complex and efficient code. Keep practicing and experimenting with functions in your JavaScript projects, and you'll quickly become more comfortable and proficient with this powerful programming tool.