0% found this document useful (0 votes)
11 views2 pages

Javascript Functions and Arrays

Uploaded by

boy346053
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views2 pages

Javascript Functions and Arrays

Uploaded by

boy346053
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 2

Creating Functions in JavaScript and Passing Arrays

In JavaScript, a function is a block of code designed to perform a particular task. To create a


function, use the 'function' keyword followed by a name, parentheses for parameters, and
curly braces for the code block. You can pass an array to a function as a parameter by simply
including the array as an argument when calling the function.

Example of Creating a Function


Here’s an example of a function that takes an array as an argument and calculates the sum
of its elements:

```javascript

function sumArray(arr) {
let sum = 0;
for (let i = 0; i < arr.length; i++) {
sum += arr[i];
}
return sum;
}

```

How to Pass an Array to a Function


To use this function, you would create an array and pass it as an argument:

```javascript

const numbers = [1, 2, 3, 4, 5];


const result = sumArray(numbers);
console.log(result); // Output: 15

```

Practice Questions
1. Write a function that takes an array of numbers as an argument and returns the sum of all
elements.

2. Create a function that calculates the average of the numbers in an array.

3. Write a function that counts the number of vowels in a string passed as an array of
characters.
4. Create a function that filters and returns only the even numbers from an array.

5. Write a function that checks if a given string is a palindrome.

You might also like