Search⌘ K

Introduction to Functions

Explore how JavaScript functions help you reuse code by processing inputs and returning outputs. Understand their role in making programs modular and maintainable, reducing repetitive code, and adjusting functionality by changing a single function.

We'll cover the following...

Background

In programming, you often need to carry out a specific task multiple times within a program. Loops help us execute the same set of instructions up to a certain number of times. However, sometimes you need to use the same set of instructions in different parts of the program. It is a tedious task to rewrite the same instructions. Let’s look at following code:

Node.js
// Find the sum
var arr = [1, 2, 3, 4]; // assign an array to arr
var sum = 0;
for(var i = 0; i < arr.length; i++){
sum += arr[i]; // Add value assigned to index i of arr to sum
}
console.log("Sum of arr:",sum); // Print the sum of arr

The above ...