0

I'm trying to write a function to add a "1" to the start and end of an array.

Code I tried:

var addTwo = function(array) { 

    var myArray = array;
    var arrayLength;

    arrayLength = array.unshift(1);
    arrayLength = array.push(1);
    return myArray;
};
8
  • 3
    This is not java! Commented Aug 29, 2016 at 8:37
  • 4
    Are you sure this is Java, not Java Script? Commented Aug 29, 2016 at 8:37
  • 1
    That's great, I love SO! Commented Aug 29, 2016 at 8:41
  • "Code I tried" And? What happened when you tried it? What issues are you running into? Commented Aug 29, 2016 at 8:43
  • Note: The myArray; at the end of the function doesn't do anything. In particular, it doesn't return the value of myArray. If you want to return the array reference, do return myArray; Commented Aug 29, 2016 at 8:44

1 Answer 1

1

The only issues I can see with your function are that you're doing

myArray;

at the end, which doesn't do anything useful, you're not using the arrayLength variable for anything, and you don't need the myArray variable. The unshift and push are fine.

So perhaps:

var addTwo = function(array) { 
    array.unshift(1);
    array.push(1);
    return array;
};

The only reason you need to return array is if the caller doesn't already have a handy reference to it.

Usage examples:

var a = ["apple","orange","banana"];
addTwo(a);
console.log(a); // [1, "apple", "orange", "banana", 1]

var addTwo = function(array) {
  array.unshift(1);
  array.push(1);
  return array;
};

var a = ["apple","orange","banana"];
addTwo(a);
console.log(a); // [1, "apple", "orange", "banana", 1]

and

var a = addTwo(["apple","orange","banana"]);
console.log(a); // [1, "apple", "orange", "banana", 1]

var addTwo = function(array) {
  array.unshift(1);
  array.push(1);
  return array;
};

var a = addTwo(["apple","orange","banana"]);
console.log(a); // [1, "apple", "orange", "banana", 1]

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you i was confused I would like to show you a screenshot to explain why i typed my code the way i did

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.