Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

brandonlind2
brandonlind2
7,823 Points

Whats the difference between a function and an array?

They both seem too do similar things

2 Answers

Stephen Layton
Stephen Layton
8,643 Points

At its most basic an array is simply a list of items. For instance apple, orange, pear. A function on the other hand is a block of code which performs operations. Say we wanted a function that added together two numbers, 1 and 2. We could so something like

function addEmUp(a, b) {
  return a + b;
}

So in var result = addEmUp(1, 3) the result variable would be assigned 4. Hope that helps.

luis betancourt
luis betancourt
1,236 Points

you use arrays to store information: lets say you want to you want to load the pictures for an image gallery on your website well you could store the image filenames in an array like this

var images = ['image1.jpg','image2.jpg','image3.jpg'];

a function performs an action, in the function below , a for loop is used to display each array item in the console.

// note that the parameter being passed is the images array that was defined above function displayImageNames(images){

var images = ['image1.jpg','image2.jpg','image3.jpg'];
   function displayImageNames(images){
            for(var i =0; i < images.length; i++){
                console.log(images[i]);
            }
        }

       displayImageNames(images);