FAQ: Arrays - Arrays and Functions

You can directly change values in an array.

const arr = [1, 2 , 3, 4, 5];
arr[0] = arr[0] +1;  //this will add 1 to the value in index 0 (1 + 1)
console.log(arr);   //this would output [2, 2, 3, 4, 5]

Array methods take functions to do more complex logic.

const arr = [1, 2 , 3, 4, 5];
const addOne = arr.map(num => num + 1); //this adds 1 to every value within arr
console.log(addOne);   //this logs [2, 3, 4, 5, 6]

These array methods make it easy to use logic on the values in an array. You could create your own function to do this but it would be a little more cumbersome.

This is a how you could make a new array with some logic to change each value but without using the Array.map() method:

const arr = [1, 2 , 3, 4, 5];

const addOne = () =>{
   const copyArr = arr.slice();  //make a copy of the array (you can skip this step if you want to directly change the original array)
   for( let i = 0; i < copyArr.length; i++ ){   //loop over every index of the array
      copyArr[i] = copyArr[i] + 1;    //add one to each index
   }
   return copyArr;  //return the new array
};
const newArr = addOne(arr);  //call the function on the original array
console.log(newArr);     // this will log [2, 3, 4, 5, 6]

This will make a lot more sense when you get further into this course.

Hi.
I’ve got an odd question. I know that variables declared within a function are deleted when the function finishes executing. Also I think I have this right about arrays; when an array is created and assigned to a variable, that variable actually just stores a key of sorts to access the data of the array. The odd question then: If an array were created and assigned to a variable within a function, when the function finishes executing is it just that key that is deleted and an inaccessible array is left in the computer’s memory, or does the data of the array get deleted as well?

1 Like

All memory reserved for a function is given back when the function is exited. Any arrays and their contents would be lost.

1 Like

Hello Codecademyans!

Arrays Excercise 10

completed all check points, and here is my code,

const concept = ['arrays', 'can', 'be', 'mutated'];

function changeArr(arr){
    arr[3] = 'MUTATED';
}

changeArr(concept);

console.log(changeArr(concept));

function removeElement(newArr) {
  newArr.pop();
}

removeElement(concept);
console.log(removeElement(concept));

but my output is

undefined
undefined

what am I missing to define here?

Thank you!

Neither function has a return. The demonstration is to show how mutating an array that is passed to a function by reference will affect the global object, even without returning it. Don’t log the function call expression, just the array.

console.log(concept)

Thank you for the prompt response. Appreciated.

1 Like

Hi everyone.
I competed this exercise. Then I wanted to see if I could also “re-assign” an array within a function.
We previously saw how this made a difference when defining an array with either const or let, so I wanted to check it out within the function.
I think my code is correct, to try and achieve this, but it doesn’t do anything.
It doesn’t modify the array or cause an error.

So I guess my question is, can you re-assign arrays within a function. And if so, how?
I’ll leave the code a wrote below, as maybe I made a mistake.
Thanks

const mynewArr = [1,'two',null]; // array with different datatypes
console.log(mynewArr); // log it 

function callError(passArr){ //function that should modify to whole array to just 'change'
  passArr = ['change'];
}

callError(mynewArr); // call the function
console.log(mynewArr); // log the result

have you find the answer for this ??

Hello, I’m having a hard time understanding this paragraph. Will someone please help me to piece it apart?

“So when you pass an array into a function, if the array is mutated inside the function, that change will be maintained outside the function as well. You might also see this concept explained as pass-by-reference since what we’re actually passing the function is a reference to where the variable memory is stored and changing the memory.”

Thank you :sunglasses:

I’ll give this a try. The array is declared in the global scope, thus this variable’s memory is global. When a function changes a variable stored on the global scope, it is retained in the variable’s memory. Hope that helps :slightly_smiling_face:

Thank you Jeffa, that actually seems very simple now that you’ve explained it.

1 Like

That’s actually not what’s going on here - saying that the function can change the variable because the variable lives in the global scope is not an accurate explanation.

Consider:

function addFortyTwo(someNumber){
   return someNumber + 42;
}

function appendFortyTwo(someArray){
  someArray.push(42);
}

// Immutable / primitive  - 'pass by value'
const myNumber = 22;
const anotherNumber = addFortyTwo(someNumber);  // pass the value 22, get back 64
console.log(myNumber); // still 22 
console.log(anotherNumber); // 64


// Mutable - 'Pass by reference'
const myArray = [1, 2, 3];
console.log(myArray); // 1, 2, 3
addFortyTwo(myArray);
console.log(myArray); // 1, 2, 3, 42

When we pass a number into addFortyTwo, the variable someNumber is created and assigned the value we passed as an argument into the function, 22.

However when dealing with mutable datatypes such as arrays, we need to think about the pass-by-reference behavior mentioned in the lesson - the local parameter someArray is created and assigned to the actual array that we passed into it, not a copy.

I may have oversimplified the definitions a bit here, and the internet is full of debates over what the proper terminology is for these two different behaviors (pass-by-value, pass-by-reference), but here’s the part to remember:

Arrays and Objects are mutable types and they can be mutated when passed as arguments into a function call. All the simpler types (number, string, bool) cannot.

Resolving typo error in given example

function addFortyTwo(someNumber){
   return someNumber + 42;
}

function appendFortyTwo(someArray){
  someArray.push(42);
}

// Immutable / primitive  - 'pass by value'
const myNumber = 22;
const anotherNumber = addFortyTwo(myNumber);  // pass the value 22, get back 64
console.log(myNumber); // still 22 
console.log(anotherNumber); // 64


// Mutable - 'Pass by reference'
const myArray = [1, 2, 3];
console.log(myArray); // 1, 2, 3
appendFortyTwo(myArray);
console.log(myArray); // 1, 2, 3, 42
1 Like

Hi, I don’t understand when we use const and when we use function to define functions. I know const and let are types of variables but in this exercise, the array was defined as const. But then after that, the function changeArr was just defined using a normal function. This is confusing me, when do I use const and when do I use function?

Either form is correct, the only difference being that a declared function is not an expression.

function foo () {}            =>  function declaration
const foo = function () {}    =>  function expression

For all intents and purposes they both behave the same way. The recommended form is the latter (the expression assignment). As a const it cannot be reassigned or deleted.

1 Like

Right got it. Thank you so much!

1 Like

Hi there, just quick question. How comes we do need to use the keyword return in the function when working with arrays?

const removeElement = newArr => {
newArr.pop();
}

It has no connection to working with arrays, more to do with enclosing the function body in curly braces. Your function above does not return anything, and should function as expected: The array should have one less element, the last one (rightmost) having been ‘popped’.

If we did include a return what would be returned?