Files
Randell Dawson 1494a50123 fix(guide): restructure curriculum guide articles (#36501)
* fix: restructure certifications guide articles
* fix: added 3 dashes line before prob expl
* fix: added 3 dashes line before hints
* fix: added 3 dashes line before solutions
2019-07-24 13:29:27 +05:30

1.4 KiB

title
title
Refactor Global Variables Out of Functions

Refactor Global Variables Out of Functions


Hints

Hint 1

  • If you're having trouble with changing bookList, try using a copy of the array in your functions.

Hint 2


Solutions

Solution 1 (Click to Show/Hide)
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.
  return newArr; // Return the new array.
}

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.
    //.
    newArr.splice(newArr.indexOf(bookName), 1); // Remove the given paramater from the new array.
    return newArr; // Return the new array.
  }
}
Solution 2 (Click to Show/Hide)
function add(list, bookName) {
  return [...list, bookName];
}

function remove(list, bookName) {
  if (list.indexOf(bookName) >= 0) {
    return list.filter(item => item !== bookName);
  }
}