Where did `arr` and `newArr` come from and what do they do or mean?


#1

Arrays and Functions

This lesson is about mutating an array. The part that I don’t understand it the parameters that are used, which are “arr” and “newArr” . Where did these come from and what do they do or mean?

In step 2 it says

" Let’s double check what happens if we mutate an array using a built-in method inside a function.

Under the console.log() statement, define another function named removeElement that takes a parameter of newArr . Inside the function body call .pop() on newArr ."

Here is the final code:

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

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

changeArr(concept);
console.log(concept);
function removeElement(newArr){
  newArr.pop();
}
removeElement(concept);
console.log(concept);

FAQ: Arrays - Arrays and Functions
FAQ: Arrays - Arrays and Functions
#2

They are arbitrarily chosen parameter names, nothing more. They will act as local variables for referencing our concept array.

.pop() will always remove the last item in the array. Just as .push() is last on, pop is last off.

function removeElement(newArr) {
  return newArr.pop()
}
console.log(removeElement(concept));
console.log(concept);
[ 'arrays', 'can', 'be', 'MUTATED' ]
MUTATED
[ 'arrays', 'can', 'be' ]

Above you’ll see how I’ve had the function return the popped value. .pop lets us assign the value we’ve taken off the array rather than just have it go into thin air. A good option to have as you will learn in your travels.


#3

I don’t understand why you can write arr[3] = … instead of concept[3] = …how does it know arr is referring to the concept array?


#4

Might one conclude that this is inside a function, where concept is the argument, and arr is the formal parameter?

removeElement(concept)

There is the argument.

function removeElement(arr) {
  // arr is a reference to `concept`
}

When concept is passed to function, only a reference is handed to the parameter, arr. Now arr refers to concept within the function. This permits changes to take place on concept, but under a different name.

Consider that since we have access to the global array object, why would we need a parameter, at all?

function changeArr(){
  concept[3] = 'MUTATED';
}
 > changeArr()
<- undefined
 > concept
<- ["arrays", "can", "be", "MUTATED"]

Can this be useful to other arrays? The function is dedicated to a single named object. Hardly a function at all.

Adding a parameter lets us use this function on any array, regardless of scope or context.