0

I am brand new to coding. Im having issues adding input to the end of my array

function my_array_add(arr, value){
   arr.push (value);
}
console.log (my_array_add(arr, 9));

I just keep getting undefined. What am I missing/doing wrong?

3
  • Return arr inside function Commented Jun 7, 2020 at 4:35
  • You must return arr;. Functions without an explicit return always implicitly return undefined. Commented Jun 7, 2020 at 4:35
  • Return fixed it! Im still getting used to all of this. Thank you for your help! Commented Jun 7, 2020 at 4:45

2 Answers 2

1

You need to return a value from your function otherwise it will return undefined:

let arr = [];

function my_array_add(arr, value){
   arr.push (value);
   return arr;
}
console.log (my_array_add(arr, 9));

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

Comments

0

If you just want to add an input to the end of an array, you can simplify the operation without writing an extra function. .push is the function you need to accomplish the desired outcome.

let arr = []; // first initialize an empty array

arr.push(input_1); // assume input_1 = 1, it can be anything in general
arr.push(input_2); // assume input_2 = 2

console.log(array); // output : [1,2]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.