7. Advanced JavaScript
Activity 8: Creating a User Tracker
Solution
- Open the
Activity08.js
file and definelogUser
. It will add the user to theuserList
argument. Make sure no duplicates are added:function logUser(userList, user) { if(!userList.includes(user)) { userList.push(user); } }
Here, we used an
includes
method to check whether the user already exists. If they don't, they will be added to our list. - Define
userLeft
. It will remove the user from theuserList
argument. If the user doesn't exist, it will do nothing:function userLeft(userList, user) { const userIndex = userList.indexOf(user); if (userIndex >= 0) { userList.splice(userIndex, 1); } }
Here, we are using
indexOf
to get the current index of the user we want to remove. If the item doesn't exist,indexOf
willreturn –1
, so we are only usingsplice
to remove the item if it exists. - Define
numUsers
, which returns the number of users currently inside the list...