An array is an indexed JavaScript collection that stores an ordered sequence of values. It can contain different types, grows or shrinks, and uses zero-based indexes. section 6.7
Common array operations include:
- Read or assign an element with brackets, inspect the number of elements with .length, and add or remove values at either end with push(), pop(), unshift(), and shift(). section 6.7
- Use slice() to create a shallow copy or to obtain a subsequence; use splice() to remove items while mutating the original array. section 6.7
- Treat arrays as general-purpose data structures for representing entities and collections that may need multiple interpretations. section 10.8
Copy-on-write mailing list
Instead of letting add_contact() reach into global state, pass it the current list, copy it with slice(), modify the copy, and return the new list: function add_contact(mailing_list, email) { var list_copy = mailing_list.slice(); list_copy.push(email); return list_copy; } The caller then assigns mailing_list = add_contact(mailing_list, email). section 6.7
var mailing_list = [];
function add_contact(mailing_list, email) {
var list_copy = mailing_list.slice();
list_copy.push(email);
return list_copy;}
function submit_form_handler(event) {
var form = event.target;
var email = form.elements["email"].value;
mailing_list = add_contact(mailing_list, email);
}
View the complete copy-on-write mailing-list implementation. section 6.7







































