Welcome back to our tutorial series on JavaScript! In the last tutorial, we learnt how to control flow using conditional statements and Loops. Now today, we are going to discuss another basic concept of JavaScript known as function. Functions are one of the most useful ways to organize and re-use code so that you can easily write clear and modular code.
What is a Function?
A function in JavaScript is a set of code that is written once but can be executed or invoked several times. Functions can be defined to accept parameters and can sometimes also return a value or execute some action and not return.
Functions
In general, a function in JavaScript is declared as follows:
You can define functions in a number of ways, though the most common is by using the function keyword:
function sayHello() {
console.log("Hello!");
}
Calling Functions
Once a function is defined, you can call it anywhere in your program by using the function name followed by parentheses:
sayHello(); // Outputs: Hello!
Functions with Parameters
Functions may have parameters. That means, you can pass data into that function so it can perform operations on that data:.
function greet(name) {
console.log("Hello, " + name + "!");
}
greet("Alice"); // Outputs: Hello, Alice!
Return Values
Functions can compute values and return them. Use the return
keyword to specify the value to return.
function add(a, b) {
return a + b;
}
let result = add(5, 3);
console.log(result); // Outputs: 8
Example Application: Calculating the Area of a Circle
Let us now create a program to solve a real-world problem using a function, that is finding the area of a circle. The area of a circle is provided by the formula πr², r being the radius of the circle.
<script>
function calculateArea(radius) {
return Math.PI * radius * radius;
}
let area = calculateArea(5);
console.log("The area of the circle is: " + area.toFixed(2)); // Displays the area of the circle, rounded to two decimal places
</script>
In this example, we defined a function called calculateArea that takes one parameter the radius of a circle quadrant, calculates and returns the area of the circle.
Summary
Functions are a cornerstone of programming in JavaScript, and they allow for enclosure and reusability of code. It will be much simpler to maintain your code should you write functions for given tasks since that makes them very modular. In future tutorials, we will go deeper into other applications of functions, that is, anonymous functions, arrow functions, and higher-order functions.
This concludes this lesson, hopefully an insightful one, but we look forward to seeing you in the next module. Keep coding!