Code Highlights logo

Learn

Arrays

Arrays and Functions

One of the most common use cases for arrays and functions is passing an array as a parameter to a function. This allows us to modify the array directly inside the function. This can be useful when we want to perform operations that change the contents of the array.

1function doubleElements(numbers) {
2 for(let i = 0; i < numbers.length; i++) {
3 numbers[i] *= 2;
4 }
5}
6
7let numbersArr = [1, 2, 3, 4, 5];
8doubleElements(numbersArr);
9console.log(numbersArr); // Output: [2, 4, 6, 8, 10]

In the above example, the function doubleElements takes an array numbers as a parameter and doubles each element in the array using a for loop. Notice that when we call the function doubleElements and pass in the numbersArr array, the array is modified directly.


Instructions

1.

Let's change the doubleNumbers function:

  • Add a parameter called num to it.
  • Return the value multiplied by 2;
2.

Call the doubleNumbers below with the second element of the numbers array and assign it to a new variable called doubledNum.

3.

Print the new doubledNum variable to the console.

Sign up to start coding

Already have an account?

Sign In

Course content