JavaScript Project Help

Hey! So I’m having quite the trouble understanding how functions and arrays work together, here are the instructions:

Create a function called numbaOne that returns the first element of an array that is passed in as a parameter.

and here’s my code:

var numbaOne = function (numbers) {
var stuff = [1,2,3,4];

console.log(numbers[0]);
}

am I anywhere in the ballpark?

The instructions say that the array is being passed in as a parameter. This means that you don’t create the array in the function. Like this:

  var numbaOne = function(numbers) {     <---- You can just define the function instead of assigning it to a var
    var stuff = [1,2,3,4];                <---- don't need this because it will be passed in to the function
    console.log(numbers[0]);              <----- this is good for the debugging but don't forget to return a value
  }

Like this:

function numbaOne(numbers) {
  return numbers[0];
}

numbaOne([1,2,3,4]);  <---- this is what calls the function

You can of course wrap it in console.log to display it.

I see so the second variable means nothing, since it requires to be passed thru a parameter, I would just
return numbers[0]

or say I wanted the 3rd element,
return numbers[2]

correct?

Hey. Let me write the code and then explain it to you:

function numbaOne(numbers) { //You create the function
return numbers[0]; //numbers will be equal to any array you pass in.
}
var stuff = [1,2,3,4];
//Now you have to CALL the function and pass an array (you can use a variable o pass the array directly)
numbaOne(stuff); //returns 1
numbaOne([5,6,7,8]); //returns 5
console.log(numbaOne(stuff) + numbaOne([5,6,7,8])); //It wil log out 6.

I hope i made myself clear, english isn’t my first language.

Edit: to your last question: Yes, that’s correct. You could also pass a parameter to define what position you want to return like:

function nthElement (numbers, index) {
return numbers[index];
}

Thank you for the help =)

As I said I really wasn’t understanding so don’t have an answer for that, I’ve got it figured out now

By the way, when you post code, you can indent it and also use the “preformatted text” button to set it apart from the rest of your message nicely. The button is on the toolbar and looks like this: </>

That way, code that looks like this (ugly):

function numbaOne(numbers) {
return numbers[0];
}

numbaOne([1,2,3,4]);
.
.
.
.

Will look like this instead (beautiful):

function numbaOne(numbers) {
  return numbers[0];
}

numbaOne([1,2,3,4]);
1 Like