Eloquent Javascript Chapter 4 Part 1
Data Structures: Objects and Arrays
Weresquirrel
Our friend Jack has a problem. Every now and then, usually between eight and ten in the evening, Jacques finds himself transforming into a small furry rodent with a bushy tail.
While turning into a weresquirrel may not be as bad as turning into a werewolf, Jacques would like to keep a daily log to narrow down the conditions that trigger the transformation.
We are going to write a program to help him track his data.
So far we have learned about:
- Numbers,
- Booleans
- strings
These are simple data types.
In order to write this program for Jack we will need to learn about more complex data structures.
- We need to store a list of days.
-
Each day will have a list of events and whether or not Jack transformed into a squirrel.
For the list of days we will use the an Array.
For each day we are going to use an Object.
Jack’s journal
var journal = [
{events: ["work", "touched tree", "pizza",
"running", "television"],
squirrel: false},
{events: ["work", "ice cream", "cauliflower",
"lasagna", "touched tree", "brushed teeth"],
squirrel: false},
{events: ["weekend", "cycling", "break",
"peanuts", "beer"],
squirrel: true},
/* and so on... */
];
We can represent Jack’s journal as an array of objects.
Data Sets: Array
"2 3 5 7 11"
Let's say we want to represent a collection of numbers: 2, 3, 5, 7, and 11.
We have learned about strings.
We could put them in a string.
But this is awkward. We would somehow have to extract them out of the string and then convert them back to a string once we were done with them.
Data Sets: Array
var listOfNumbers = [2, 3, 5, 7, 11];
console.log(listOfNumbers[1]);
// → 3
console.log(listOfNumbers[1 - 1]);
// → 2
Fortunately, Javascript provides us a data type for storing sequences of values. It's called an array.
It is written as a list of values between square brackets, separated by commas.
To access an element in the array you use a pair of square brackets immediately after an expression, with another expression inside of them.
When accessing an array the index is 0 based.
Properties
listOfNumbers.length;
// → 5
null.length;
// → TypeError: Cannot read property 'length' of null
In past examples we’ve seen a few expressions like myString.length (to get the length of a string) and Math.max (the maximum function).
These are expressions that access a property of a value.
Almost all JavaScript values have properties.
The exceptions are null and undefined.
Properties
The two most common ways to access properties in JavaScript are with a dot and with square brackets.
Both value.x and value[x] access a property on value— but not necessarily the same property.
The difference is in how x is interpreted.
Named Properties - dot
var events = ["work","television"];
var day = {
events: events,
squirrel: false
};
console.log(day.events);
// → ["work","television"]
console.log(screen.squirrel);
// → false
console.log(events.length);
// → 2
When using a dot, the part after the dot must be a valid variable name, and it names the property.
Properties - bracket
When using square brackets, the expression between the brackets is evaluated to get the property name.
"2" and "john doe" aren't valid variable names so they can't be accessed through the dot notation.
var random = {
1: "one"
"2": 2
"john doe": "unknown"
};
var x = 1;
console.log(random[x])
// → "one"
console.log(random["two"])
// → 2
console.log(random["john doe"]);
// → "unknown"
Properties on Array
var array = ["zero","one","two"];
console.log(array[0]);
// → zero
console.log(array.length);
// → 3
console.log(array["length"]);
// → 3
The elements in an array are stored in properties.
The names of these properties are numbers so we have to use the bracket syntax to access them. array[1]
The length property on an array tells us how many elements it contains.
You typically write array.length because it's easier than writing array["length"]
Methods
var doh = "Doh";
console.log(typeof doh.toUpperCase);
// → function
console.log(doh.toUpperCase());
// → "DOH"
toUpperCase is a method on string.
When called, it will return a copy of the string, in which all letters have been converted to uppercase.
In addition to values
we can also store functions as properties.
These are called methods.
More Array Methods
var mack = [];
mack.push("Mack");
mack.push("the", "Knife");
console.log(mack);
// → ["Mack", "the", "Knife"]
console.log(mack.join(" "));
// → "Mack the Knife"
console.log(mack.pop());
// → "Knife"
console.log(mack);
// → ["Mack", "the"]
Objects
var descriptions = {
work: "Went to work",
"touched tree": "Touched a tree"
};
Values of the type object are arbitrary collections of properties.
Inside the curly braces, we can give a list of properties separated by commas
Each property is made up of the following:
- name
- followed by a colon
- followed by an expression that provides a value
Properties whose names are not valid variable names or valid numbers have to be quoted.
Objects
Reading a property that doesn’t exist will produce the value undefined.
It is possible to assign a value to a property by using the = operator.
This will replace the property’s value if it already existed or create a new property on the object if it didn’t.
var day1 = {
squirrel: false,
events: ["work", "touched tree", "pizza", "running",
"television"]
};
console.log(day1.squirrel);
// → false
console.log(day1.wolf);
// → undefined
day1.wolf = false;
console.log(day1.wolf);
// → false
Objects
Property bindings are similar to variable bindings.
You may think of objects as octopuses with any number of tentacles, each of which has a name inscribed on it.
Objects
The delete operator cuts off a tentacle from such an octopus. It is a unary operator that will remove the
named property from the object.
var anObject = {left: 1, right: 2};
console.log(anObject.left);
// → 1
delete anObject.left;
console.log(anObject.left);
// → undefined
console.log("left" in anObject);
// → false
console.log("right" in anObject);
// → true
The binary in operator, when applied to a string and an object, returns a Boolean value that indicates whether that object has that property.
Arrays are actually objects
Arrays are just a kind of object specialized for storing sequences of things.
typeof [1, 2] produces "object".
You can see them as long, flat octopuses with all their arms in a neat row, labeled with numbers.
Jack’s Journal
var journal = [
{events: ["work", "touched tree", "pizza",
"running", "television"],
squirrel: false},
{events: ["work", "ice cream", "cauliflower",
"lasagna", "touched tree", "brushed teeth"],
squirrel: false},
{events: ["weekend", "cycling", "break",
"peanuts", "beer"],
squirrel: true},
/* and so on... */
];
An array of objects.
We have learned enough about arrays and objects to now put together our data structure to help Jack track the things he does daily and if he turns into a were-squirrel.
Summary
- Objects and arrays provide ways to group several values into a single value.
- Conceptually, this allows us to put a bunch of related things in a bag and run around with the bag.
- Most values in JavaScript have properties, the exceptions being null and undefined.
- Properties are accessed using value.propName or value["propName"].
- There are some named properties in arrays, such as length.
-
Methods are functions assigned to a property of an object. i.e "string".toUpperCase()
Thank You!
Eloquent Javascript Chapter 4 Part 1
By Dustin McCraw
Eloquent Javascript Chapter 4 Part 1
- 1,478