Amar Patel Amar Patel - 4 months ago 11
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];
console.log(numbaOne0);


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

Answer

First of all, this isn't a function.

A function works like this:

CODE:

//function definition
function testFunction(param){
    console.log(param);
}

//function call
testFunction("hello");

OUTPUT:

hello

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
console.log(myArray[0]);

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
console.log(firstElementOfBlunt);

OUTPUT: 1

///EDIT///

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.