Introduction

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 courseIntro to JavaScriptfor a refresher.

Remember the Array?

Thearrayis 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 calledmyArray, which is assigned to an empty array:

const myArray = [];

Each element in an array is referenced by a_numeric key_called anindex, 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 infruits, we access that element by its index:

fruits[0];

// 'apple'

Likewise, this is how we can access the last (right-most) element infruits:

fruits[4];

// 'lychee'
/*
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.
*/

const mixedArray = [23, 'MJ', true, ['celtics', 'pierce']];
  • RESET QUIZ
  • TEST RUN
  • SUBMIT ANSWER

Objects

Theobjectis 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 calledmyObject, 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, likecolororyear. 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 car object.
  • 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 ( , ). The car object therefore contains three properties.

Unlike arrays, objects are_unordered_collections. For example, thecarobject above could be written with the key/value pairs in a different order, and it wouldn't change how you'd accesscar'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 todictionariesandhashes(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 aresymbols(rather thanstrings), 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 thatobjects 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 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 asconstructors. This is an object-oriented JavaScript course, so we'll take a deep dive into these features throughout this course!

/*
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?
*/

let menu = {
    name: 'Salted Caramel Ice Cream',
    price: 2.95,
    ingredients: ['butter', 'ice cream', 'salt', 'sugar']
};
  • RESET QUIZ
  • TEST RUN
  • SUBMIT ANSWER

QUESTION 3 OF 6

Which of the following are features or characteristics of an object? Select all that apply:

  • Ordered

  • Key/value pairs

  • { Curly Braces }

  • Indexed

  • Unordered

  • [ Square Brackets ]

SUBMIT

Accessing Object Properties

So now that we know what objects look like, how do we retrieve information from them? In other words: how do weaccess their values? There are two ways:dot notationandsquare bracket notation. Consider thisbicycleobject:

const bicycle = {
  color: 'blue',
  type: 'mountain bike',
  wheels: {
    diameter: 18,
    width: 8
  }
};

Using dot notation, we can accessbicycle'scolorproperty 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 thewidthproperty of the object contained withinbicycle'swheelsproperty, 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 return8.

⚠️ 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 abovebicycleobject that is anumber. 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 declaremyVariable, 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;


// undefined

It may seem odd, but recall that all property keys in a JavaScript object arestrings, even if the quotation marks are omitted. With dot notation, the JavaScript interpreter looks for a key withinbicyclewhose value is'myVariable'. Since there isn't such a key defined in the object, the expression returnsundefined.

Reading Arrays

Write an expression to access the last item in the following array:

const mileTimes = [7.50, 6.25, 10.60, 8.88];

mileTimes[3];

RESET

Reading Objects

Write an expression to access the value of thepopulationobject'sbrazilproperty:

const populations = {
  china: 1379000000,
  brazil: 207700000,
  india: 1324000000,
  unitedStates: 323100000
};

populations['brazil'];

RESET

Reading Nested Objects

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'
  }
};

greetings.hello.portuguese;

RESET

Summary

In JavaScript, anobjectis 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 eithersquare bracket notationordot notation. For a closer look at object fundamentals, check outIntro to JavaScriptlinked 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!

Further Research

results matching ""

    No results matching ""