To efficiently gather data and add it to a collection, you'll need a loop with an exit condition and a function specifically designed for updating the contacts
list.
In Javascript, it's customary to name variables starting with a lowercase letter. Uppercase letters typically signify constructible functions or classes, while all caps are usually reserved for constant values.
This method leverages short hand properties in objects, where variables automatically become object properties with identical names.
When validating the loop
, it uses the optional chaining operator ?.
. This is necessary because prompt
may return null
, which cannot be converted to uppercase for comparison purposes.
function addContact(firstname, lastname, data) {
contacts.push({ firstname, lastname, data });
}
const contacts = [];
let loop;
do {
addContact(
prompt("Enter first name"),
prompt("Enter last name"),
prompt("Please provide some data")
);
loop = prompt('Add another contact? [Y/N]', 'N');
if (loop?.toUpperCase() === 'N') loop = false;
} while (loop)
console.log(contacts);