Pass By Value VS Pass By Reference

Tell us what’s happening:

What situations cause pass by reference and what situations cause pass by value ?
I know pass by reference means changes in the value of a variable in the functions also affect the actual value of that variable outside of the function scope.

I believe the functions in this code pass the arguments by means of pass by reference. Is there a way I can know how functions pass their arguments?
Your code so far

console.clear();

var bookList = ["The Hound of the Baskervilles", "On The Electrodynamics of Moving Bodies", "Philosophiæ Naturalis Principia Mathematica", "Disquisitiones Arithmeticae"];

function add(arr, bookName) {
let newArr = [...arr]; 
newArr.push(bookName); 
return newArr; 
}

function remove(arr, bookName) {
let newArr = [...arr]; 
if (newArr.indexOf(bookName) >= 0) {
  newArr.splice(newArr.indexOf(bookName), 1); 
  return newArr; 
}
}

var newBookList = add(bookList, 'A Brief History of Time');
var newerBookList = remove(bookList, 'On The Electrodynamics of Moving Bodies');
var newestBookList = remove(add(bookList, 'A Brief History of Time'), 'On The Electrodynamics of Moving Bodies');

console.log(bookList);
console.log(newBookList);
console.log(newerBookList);
console.log(newestBookList);

Challenge: Refactor Global Variables Out of Functions

Link to the challenge:

primitive values (numbers, strings, boleans, undefined, null…) are passed by value, objects, arrays, functions are passed by reference

so here, that you are working with the bookList array, if it is passed as function argument, and the function make changes to the parameter, the global array is also changed, so to avoid that you need to make sure that the parameter is not changed, creating a new array in some way

1 Like

Thanks for the reply.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.