Data Structures: Arrays and Objects

In Unit 3, you learned about JavaScript primitive data types such as strings, numbers, and Booleans. In addition, this unit introduces the "array" and "object" data types. 

Why use objects?

  • Objects are an essential data type of JavaScript, and learning how to use them is necessary to develop applications.
  • Objects help programmers write reusable code for real-world objects. 
  • Objects are dynamic; you can create, add, and delete them.

Both string and array values contain, in addition to the length property, a number of properties that hold function values.

let doh = "Doh";
console.log(typeof doh.toUpperCase);
// → function
console.log(doh.toUpperCase());
// → DOH

Every string has a toUpperCase property. When called, it will return a copy of the string in which all letters have been converted to uppercase. There is also toLowerCase, going the other way.

Interestingly, even though the call to toUpperCase does not pass any arguments, the function somehow has access to the string "Doh", the value whose property we called.

Properties that contain functions are generally called methods of the value they belong to, as in "toUpperCase is a method of a string".

This example demonstrates two methods you can use to manipulate arrays:

let sequence = [1, 2, 3];
sequence.push(4);
sequence.push(5);
console.log(sequence);
// → [1, 2, 3, 4, 5]
console.log(sequence.pop());
// → 5
console.log(sequence);
// → [1, 2, 3, 4]

The push method adds values to the end of an array, and the pop method does the opposite, removing the last value in the array and returning it.

These somewhat silly names are the traditional terms for operations on a stack. A stack, in programming, is a data structure that allows you to push values into it and pop them out again in the opposite order so that the thing that was added last is removed first. These are common in programming – you might remember the function call stack from the previous chapter, which is an instance of the same idea.