Let’s jump back to functions and return values for a moment to have a look at an applied example how functions and return value can help you writing less code.
In this example we want to get a random element from an array when calling a function. We will use some of the things we have learned so far to achieve that.
1
2
3
4
5
6
7
8
function randomElement(array) {
let randomIndex = Math.floor(Math.random() * array.length);
return array[randomIndex];
}
let animals = ["🐹", "🐶", "🐰", "🐱", "🐵", "🦁"];
let randomAnimal = randomElement(animals);
console.log(randomAnimal);
This function can be used now with every array. This way the return keyword helps us to write code that we can reuse more easily.