01. Introduction
OOJS L1 1 - Course Intro
Course Structure
Welcome! This course covers object-oriented programming with JavaScript. Here's a quick breakdown of what each of the lessons in the course looks like:
- Lesson 1 details how to create, access, and modify objects.
- Lesson 2 examines how JavaScript functions are first-class functions.
- Lesson 3 illustrates JavaScript's abstractions over traditional classes and inheritance.
Starting Off
First, let's make sure we're all on the same page on some object fundamentals. Most of the material on this page should be review. If things feel largely unfamiliar as you go through the content, feel free to check out our course Intro to JavaScript for a refresher.
Remember the Array?
The array is one of the most useful data structures in JavaScript. At its core, an array is just an ordered collection of elements, enclosed by square brackets (i.e., [ and ]). Here's a variable called myArray, which is assigned to an empty array:
const myArray = [];
Each element in an array is referenced by a numeric key called an index, which starts from zero and increments by one for each additional element in the array. Check out the following example:
const fruits = ['apple', 'banana', 'orange', 'grape', 'lychee'];
console.log(fruits);
// ['apple', 'banana', 'orange', 'grape', `lychee`]
If we want to retrieve the first (left-most) element in fruits, we access that element by its index:
fruits[0];
// 'apple'
Likewise, this is how we can access the last (right-most) element in fruits:
fruits[4];
// 'lychee'
Start Quiz:
/*
Recall that arrays can store many different types of data, not just strings!
Below, create an array called `mixedArray` that contains:
* A number
* A string
* A boolean
* Another array
The order and length of the array are up to you; just be sure to include
at least one of each data type listed above.
*/
Objects
The object is one of the most important data structures in JavaScript. After all, you're currently taking an entire course on object-oriented programming!
Fundamentally, an object is a collection of associated key/value pairs. We create an object with curly brackets (i.e., { and }). Here's a variable called myObject, which is assigned to an empty object:
const myObject = {};
While elements in arrays are referenced by a numeric index, keys in an object must be named explicitly, like color or year. Check out the following example:
const car = {
color: 'red',
year: 1992,
isPreOwned: true
};
Let's break this down and see what's going on:
- The variable that is assigned to the object is named
car. - Curly brackets are used to define the
carobject. - Individual keys (e,g,
color) are associated with a single value ('red'in this case). These key/value pairs are connected by a colon (:). - Each distinct key/value pair, known as a property of that object, is separated from other properties by a comma (
,). Thecarobject therefore contains three properties.
Unlike arrays, objects are unordered collections. For example, the car object above could be written with the key/value pairs in a different order, and it wouldn't change how you'd access car's items:
const car = {
isPreOwned: true,
color: 'red',
year: 1992
};
Object Property Syntax
Another thing to note is that keys (i.e., the names of the object's properties) are strings, but quotation marks surrounding these strings are optional as long as the string is also a valid Javascript identifier (i.e., you could use it as a variable name or function name). As a result, the following three objects are equivalent:
const course = { courseId: 711 }; // ← no quotes around the courseId key
const course = { 'courseId': 711 }; // ← single quotes around the courseId key
const course = { "courseId": 711 }; // ← double quotes around the courseId key
You'll commonly find quotation marks omitted from property names. Certain situations require them to be included, especially if the property name:
- Is a reserved word (e.g.,
for,if,let,true, etc.). - Contains spaces or special characters that cannot appear in a variable name (i.e., punctuation other than
$, and_-- most accented characters).
For the exact rules for property names, feel free to check out the links at the end of this section.
💡 JavaScript Objects Might Look Familiar 💡
If you've had past experience with Python or Ruby, objects are quite similar to dictionaries and hashes (respectively). Though they may look the same, there are key differences to be mindful of.
First, Ruby hashes and JavaScript objects have similar functionality: they are both collections of values accessible by keys. However, values are accessed in Ruby hashes a bit differently. Consider the following Ruby hash:
book = {
title: 'To Kill a Mockingbird',
author: 'Harper Lee',
published: 1960
}
Because the hash keys are symbols (rather than strings), properties are accessed by that symbol:
book[:title]
# 'To Kill a Mockingbird'
Any attempts to using JavaScript's dot notation or square bracket notation lead to undesirable results:
book.title
# undefined method `title' for #<Hash> (NoMethodError)
book['title']
# nil
Another major difference between Ruby hashes and JavaScript objects are that objects can take a function as a property value (we'll take a deep dive into this in the next section). This functionality does not exist for Ruby hashes!
On the other hand, Python dictionaries have some similar functionality to objects in JavaScript as well, with some notable differences. For one, keys in Python dictionaries must be something hashable (e.g., a string, a number, a float, etc.). The following is a valid object in JavaScript:
const javascriptObject = { name: 'George Orwell', year: 1984 }
However, it would be invalid as a Python dictionary:
python_dictionary = {name: 'George Orwell', year: 1984}
# Traceback (most recent call last):
# NameError: name 'name' is not defined
A quick fix would be to convert the Python dictionary's keys into strings:
my_dictionary = {'name': 'George Orwell', 'year': 1984}
Above all else, you can also leverage objects in JavaScript not just to hold data, but for many powerful functionalities such as constructors. This is an object-oriented JavaScript course, so we'll take a deep dive into these features throughout this course!
Start Quiz:
/*
Create an object called `menu` that represents the following menu item:
Salted Caramel Ice Cream
2.95
butter, ice cream, salt, sugar
The object should contain the following properties:
* name
* price
* ingredients
Hint: Which data collection can hold all the listed ingredients in order?
*/
Object Features vs. Array Features
SOLUTION:
- Key/value pairs
- { Curly Braces }
- Unordered
Accessing Object Properties
So now that we know what objects look like, how do we retrieve information from them? In other words: how do we access their values? There are two ways: dot notation and square bracket notation. Consider this bicycle object:
const bicycle = {
color: 'blue',
type: 'mountain bike',
wheels: {
diameter: 18,
width: 8
}
};
Using dot notation, we can access bicycle's color property by writing:
bicycle.color;
// 'blue'
Similarly, we can access the same property using square bracket notation by writing:
bicycle['color'];
// 'blue'
Both expressions are equivalent, and will each return 'blue'.
What about nested objects? To retrieve the value of the width property of the object contained within bicycle's wheels property, you can do the following with dot notation:
bicycle.wheels.width;
// 8
And with square bracket notation:
bicycle['wheels']['width'];
// 8
Again, both expressions are equivalent, and will each return 8.
⚠️ Dot Notation Limitations ⚠️
Note that while dot notation may be easier to read and write, it can't be used in every situation. For example, let's say there's a key in the above
bicycleobject that is a number. An expression likebicycle.1;will cause a error, whilebicycle[1];returns the intended value:bicycle.1; // Uncaught SyntaxError: Unexpected number bicycle[1]; // (returns the value of the `1` property)Another issue is when variables are assigned to property names. Let's say we declare
myVariable, and assign it to the string'color':const myVariable = 'color';
bicycle[myVariable];returns'blue'because the variablemyVariablegets substituted with its value (the string'color') andbicycle['color']'s value is'blue'. However,bicycle.myVariable;returnsundefined:bicycle[myVariable]; // 'blue' bicycle.myVariable; // undefinedIt may seem odd, but recall that all property keys in a JavaScript object are strings, even if the quotation marks are omitted. With dot notation, the JavaScript interpreter looks for a key within
bicyclewhose value is'myVariable'. Since there isn't such a key defined in the object, the expression returnsundefined.
Reading Arrays
QUESTION:
Write an expression to access the last item in the following array:
const mileTimes = [7.50, 6.25, 10.60, 8.88];
SOLUTION:
NOTE: The solutions are expressed in RegEx pattern. Udacity uses these patterns to check the given answer
Reading Objects
QUESTION:
Write an expression to access the value of the population object's brazil property:
const populations = {
china: 1379000000,
brazil: 207700000,
india: 1324000000,
unitedStates: 323100000
};
SOLUTION:
NOTE: The solutions are expressed in RegEx pattern. Udacity uses these patterns to check the given answer
Reading Nested Objects
QUESTION:
Write an expression that outputs how to say hello in Portuguese:
const greetings = {
hello: {
english: 'hi',
french: 'bonjour',
portuguese: 'oi'
},
goodbye: {
english: 'bye',
french: 'au revoir',
portuguese: 'tchau'
}
};
SOLUTION:
NOTE: The solutions are expressed in RegEx pattern. Udacity uses these patterns to check the given answer
Summary
In JavaScript, an object is an unordered collection of properties. Each property consists of a key/value pair, and can reference either a primitive (e.g., strings, numbers, booleans, etc.) or another object. Unlike elements in an array, which are accessed by a numeric index, properties in objects are accessed by their key name using either square bracket notation or dot notation. For a closer look at object fundamentals, check out Intro to JavaScript linked below.
Now that we know how to read existing properties in an object, how do we go about creating new properties? What about modifying existing properties, or even adding and removing properties altogether? We'll answer all this and more in the very next section!