JavaScript Refresh – Objects and Arrays

Objects and arrays let us group values to build more complex structures.

Data Sets

Arrays are used to represent a collection of data. It’s a list of values.

const numArr = [5, 7, 10];

Arrays use zero-based counting.

Properties

All JS values (numbers, strings, arrays, etc) have properties except for null and undefined which throw an error.

null.length throws an error.

Arrays are a type of value. Our numArr variable points to an array that we created.

We added three properties to the array (5, 7, 10), but the array has many other useful properties. One of those is the length property.

Property Names

The word “length” is the name of the property. It’s not the property itself.

You can access properties using the name of the property. The name of the property, in this case is “length”.

Property names can be strings or numbers.

You can access properties in two different ways. You can use a dot and the name of the property or the number of the property surrounded by square brackets. If you use a dot (dot notation), the property name can’t have any spaces.

numArr.length or numArr['length']

If we wanted to access one of the properties that we added to the numArray, we’d use a number.

In arrays, the elements we add are properties, and the numbers are the property names.

In the numArr array, the first element is the number 5, and the property name would be 0.

numArray["length"]; // 3
numArray.length // 3

Methods

Properties of a value can be anything. Properties that are functions are called methods.

“word”.toUppercase();

The toUppercase function is a property of the “word” string.

The push method adds an element to the end of an array. The pop method removes the last element and returns it.

The push and pop methods are traditional names for adding to and removing from a stack. A stack is a data structure that lets you add to it and remove from it.

Objects

Objects are another type of value. They are a random collection of properties.

const note = {
    isVisible: true,
    content: "the text of the note"
};

The Parts of an Object

  • Braces
  • Property name
  • Colon
  • Property value
  • Comma

In JS, braces can be used to start a block of statements or create an object.

If you try to access a property that doesn’t exist, you get undefined.

note.title = "day one";

You can use an equals sign to assign a value to a property name.

Just like other bindings, property bindings (like the title binding) grasp values. Other properties and bindings might be grasping the same value.

delete note.title;

To delete a property name and its value, use the delete unary operator.

Object.keys(note);

Use the keys function to find the property names in an object.

let extendedNote = { date: "2021-01-01" };
Object.assign(extendedNote, note};

typeof []; // object

Arrays are just a specialized type of object.

Mutability

Number, string, and Boolean values are immutable. When you create a string, it never changes.

Objects are mutable. You can change its properties.

const obj1 = { value: 10; }
const obj2 = obj1;
const obj3 = { value: 10 }; 
obj2.value = 15;

Both obj1 and obj2 grasp the same value.

const farm = { crop: "corn" };
farm.crop = "tomatos";

The variable still refers to the same object which is why it’s okay to change the values of one of its properties.

farm = {crop: "beans"};

This would throw an error because we’re changing the object.

obj1 === obj3; // false

Even if two objects have identical properties, their identities will be different. They will be different objects.

let journal = [];
function addEntry(events, squirrel) {
    journal.push({ events, squirrel });
}

The name of the variable is used as the property name.

Array Loops

for (let i = 0; i < journal.length; i++) {
  let entry = journal[i];
}

for (let entry of journal) {
  // do something with entry
}

These are the same.

Array Methods

  • shift/unshift: Add/remove from the start of an array.
  • indexOf
  • slice: [0, 1, 2, 3, 4] .slice(2,4); // [2,3]
  • concat

String Properties

The string, number, and Boolean value types are not objects.

  • slice
  • indexOf
  • trim: remove white space from beginning and end of a string
  • join
  • split
  • repeat

Rest parameters

function combine(...words) {
  //
}

Let a function take any number of arguments using a rest (…) parameter. The special rest parameter has to be the last argument.

The arguments in the rest parameter are put into an array.

let words = ["one", "two", "three"];
combine(words);

You can use a similar method to undo (or “spread”) an array to act like separate arguments.

[…words, “four’, “five”] ;

You can also spread out an array into another

The Math Object

The math object is used to namespace useful mathematical functions.

  • max
  • min
  • cos
  • sin
  • tan
  • PI
  • random
  • floor
  • ceil
  • round
  • abs

Destructuring

function example ([first, second], another) {
    return first + another + second + another;
}

function example (stuff, another) {
    return stuff[0] + another + stuff[1] + another;
}

function example (stuff, another) {
    const first = stuff[0];
    const second = stuff[1];
    return first + another + second + another;
}

function example (stuff, another) {
    const [first, second] = stuff;
    return first + another + second + another;
}

The four functions are the same, but in one, we are destructuring the array as an argument. In another, we destructure the array in the function. The other two use a more obvious approach to access the elements in the array.

You can do the same thing with objects.

const { title } = { title: "A note" };

JSON

Objects and arrays are made up of bits and binary in the computer’s memory. If we want to send these structures somewhere, we have to serialize it. JSON (JavaScript Object Notation) is one popular serialization format.

All property names have to be surrounded by double quotes.

You can only serialize simple data expressions: no function calls, bindings, or computations.

  • JSON.stringify
  • JSON.parse