2018-10-12 15:37:13 -04:00
---
title: Refactor Global Variables Out of Functions
---
2019-07-24 00:59:27 -07:00
# Refactor Global Variables Out of Functions
2018-10-12 15:37:13 -04:00
2019-07-24 00:59:27 -07:00
---
## Hints
### Hint 1
2018-10-12 15:37:13 -04:00
- If you're having trouble with changing bookList, try using a copy of the array in your functions.
2019-07-24 00:59:27 -07:00
### Hint 2
2018-10-12 15:37:13 -04:00
- Here's some more information about [how JavaScript handles function arguments ](https://codeburst.io/javascript-passing-by-value-vs- reference-explained-in-plain-english-8d00fd06a47c ).
2019-07-24 00:59:27 -07:00
---
## Solutions
< details > < summary > Solution 1 (Click to Show/Hide)< / summary >
2018-10-12 15:37:13 -04:00
```javascript
2019-07-24 00:59:27 -07:00
function add(arr, bookName) {
let newArr = [...arr]; // Copy the bookList array to a new array.
newArr.push(bookName); // Add bookName parameter to the end of the new array.
2018-10-12 15:37:13 -04:00
return newArr; // Return the new array.
}
2019-07-24 00:59:27 -07:00
function remove(arr, bookName) {
let newArr = [...arr]; // Copy the bookList array to a new array.
if (newArr.indexOf(bookName) >= 0) {
// Check whether the bookName parameter is in new array.
//.
2018-10-12 15:37:13 -04:00
newArr.splice(newArr.indexOf(bookName), 1); // Remove the given paramater from the new array.
return newArr; // Return the new array.
2019-07-24 00:59:27 -07:00
}
2018-10-12 15:37:13 -04:00
}
```
2019-07-24 00:59:27 -07:00
< / details >
< details > < summary > Solution 2 (Click to Show/Hide)< / summary >
2018-10-12 15:37:13 -04:00
```javascript
2019-07-24 00:59:27 -07:00
function add(list, bookName) {
2018-10-12 15:37:13 -04:00
return [...list, bookName];
}
2019-07-24 00:59:27 -07:00
function remove(list, bookName) {
2018-10-12 15:37:13 -04:00
if (list.indexOf(bookName) >= 0) {
2019-07-24 00:59:27 -07:00
return list.filter(item => item !== bookName);
}
2018-10-12 15:37:13 -04:00
}
```
2019-07-24 00:59:27 -07:00
< / details >