JavaScript – Objects and Arrays

Objects let us group values to build more complex structures.

Objects

Objects are a type of value. They’re a random collection of properties.

const note = {
    isPrivate: true,
    content: "secret"
};

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.

Properties

All JS values have properties except for null and undefined which throw an error.

null.length throws an error.

You can access a property with a dot or square brackets.

anyvalue.x or anyvalue ['x']

Properties are named, and you access them using their names. The anyvalue variable has a property called ‘x’.

Property Names

Property names are strings, but dot notation only works with names that look like bindings.

In arrays, the elements are the 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.

Arrays have other properties besides the elements in it. The length property none gets the number of elements in the array.

You could also do numArray[“length”] which would return 3 since there are three elements in the array.

Methods

String and array values have a length property. The length property points to a number value, but string and array values have other properties that are functions.

“word”.toUppercase();

toUppercase is a property of the “word” string.

Each property has a type. The toUppercase property is a function.

When a property is a function, it’s called a method.

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.

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.

Data Sets

Represent a collection of data with an array. An array is a list of values.

const numArr = [5, 7, 10];

Arrays use zero-based counting.

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