Amar Patel Amar Patel - 1 year ago 50
Javascript Question

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

This should work for an array of any size.

My solution:

var numbaOne = [1,2,3];

Why doesn't that work? I tried it in and it worked.

Answer Source

First of all, this isn't a function.

A function works like this:


//function definition
function testFunction(param){

//function call



But there are a few more issues. var numbaOne = [1,2,3]; is fine and appropriately gangsta. But the second part is not a valid JavaScript statement.

You access an array this way:

//define array
var myArray = [1,2,3];

//get an element of that array

Those brackets [] are the important part.

Your Function

So for your example, if you wanted a function that returned the first element of an array passed as a parameter, you would want something like this:

//make dat function
function numbaOne(myArrayHomie){
    //return the first element of what was passed to the function
    return myArrayHomie[0];

If we were to use this function, it would look something like this:

//some array
var blunt = [1,2,3];

//call the function and store result in a variable
var firstElementOfBlunt = numbaOne(blunt);

//print dat



Since it's a function, you can use that as many times as you want.

console.log(numbaOne(['my', 'homie', 'g']));

would print out my. That's what we mean by a function. You're putting that code block into something reusable, so that you could pass numbaOne any array and have it always return the first element.