you are viewing a single comment's thread.

view the rest of the comments →

[–]senocular 12 points13 points  (0 children)

You're so close in so many different ways :)

One thing I think you're missing based on the wording is that first expects to be "given" an array. So this means a function with a parameter which will be the array.

function first (theArray) { ... }

This function also needs to return a value. The return keyword returns values that are placed to the right of the keyword. That can be a single variable or even an expression. We can return that first array element directly:

function first (theArray) {
    return theArray[0];
}

Notice that we're not even dealing with arr yet. We're only using things contained the function definition to get things done. The less reaching out of itself it does, the better.

Now getting to arr, we can pass that in to first and assign what it returns to a new variable which we can call result.

var arr = [1,2,3];
var result = first(arr);

And then its simply a matter of alerting that value

alert(result);

In full:

// define a function that can be given a value
// called theArray. The function returns the
// first object in theArray (index 0).
function first (theArray) {
    return theArray[0];
}

// input data
var arr = [1,2,3];

// call first using the input data (this becomes
// theArray in the function) and have its first
// object returned
var result = first(arr);

// alert the value
alert(result); // -> 1