Introduction to Functions

Introduction to functions.

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:

Press + to interact
// 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 ...