Section 1

Intro to JavaScript Objects




Lesson Setup

For this lesson, we're going to code along using an HTML, CSS & JS REPL from repl.it -- you can name it "JavaScript Objects Practice".`




What Are Objects?

  • Objects are the most common data structure in Object Oriented Programming (OOP)
  • Very simply, objects are a collection of zero or more properties
  • So what's a property? A property consists of a key: value pair, where the:

    • key is a string (JS will coerce the type automatically), and the
    • value is any JS expression (code that evaluates to a single value or thing), including other objects (yes, functions too)
  • In computer science, collections of key/value pairs are commonly referred to as dictionaries - a good visualization of what an object is




Why Objects?

  • In OOP, we often model the goal of our application using real-world objects
  • We use Objects in our code to describe Nouns like we use functions to describe Verbs and arrays to be lists of nouns



Lesson Objectives

After this lesson, students will be able to:

  1. Explain the difference between arrays and objects
  2. Store key-value pairs inside an object
  3. Access values by key-name
  4. Add Object Properties
  5. Change Object Properties
  6. Explain why we use an object instead of an array
  7. Manipulate objects and arrays declared as const
  8. List common errors made with objects
  9. Use object properties with conditionals

Explain the difference between arrays and objects

We have seen the following datatypes:

  • String
  • Number
  • Boolean

Arrays are a data structure. We use them to organize our data: in the case of arrays, we can organize our data into a sequential list data structure.

  • We can use arrays to store multiple pieces of data as a sequential list:
const vehicle = ["blue", 4000, 1989];
  • Each element has a corresponding index (or place), in sequence.

But with the array above, we don't know what the values mean. Does "blue" refer to the color of the vehicle? To the mood of the owner? Is it the model of the vehicle?

  • An object is also a data structure, but we can use objects to store data with greater specificity.
  • In JavaScript, objects are what we use to represent key-value pairs.

Store key-value pairs inside an object

Key-value pair syntax:

const car = {
	color: "blue",
	hp: 4000,
	year: 1989
}
  • Unlike arrays, objects use named keys rather than ordered indexes. Each piece of data is bound to its key, rather than assigned an index. The data is not sequential.
  • In Javascript, an object is a way to group many pairs of keys and values together

We can console.log the entire object:

console.log(car);

Access values by key-name

We can access the values stored in key using dot notation:

console.log(car.color)

DIFFERENCES BETWEEN ARRAYS AND OBJECTS

  • Arrays are declared using the square brackets const arr = [];
  • Objects are declared using the curly braces const obj = {}

Objects contain key-value pairs. They are are the properties of the object

A key is like an index in an array, but it has

  • a name
  • it is unique

A key is really a string but we can omit the quotes.

A value is what a key refers to, and can be any datatype.

Add Object Properties

You can easily add more properties to a previously declared object:

const house = {
	doors: 9
}

console.log(house)

=> { doors: 9 }

Add properties to the house object by simply adding a key using dot notation and the value using an equals =. Our house has no windows. Let's add some in without writing them straight into the object:

house.windows = 30

When we do it this way, the windows key is added to the object.

console.log(house);

=> { doors: 9, windows: 30 }

Add another property hasGarden:

house.hasGarden = true;

Change Object Properties

Changing the value of an existing key has the same syntax as creating a new key-value pair:

const bicycle = {
	isATricycle: false
}
bicycle.isATricycle = true

Explain why we use an object instead of an array

When designing your programs, it is up to you to choose how to model your data. We can represent real-life things with our datatypes, but it's a matter of choosing the appropriate datatypes.

If the thing you want to model is just a list, use an array.

If the thing want to model has properties, use an object.

And for more simple things use Strings, Numbers, Booleans

Using what we know about datatypes so far, which datatype would we use to model:

  1. The name of your cat
  2. The age of your cat
  3. Your cat's favorite things
  4. Whether your cat can speak French
  5. Whether your cat can solve a Rubik's cube
  6. Your cat

Manipulate objects and arrays declared as const

const only prevents you from reassigning a variable, it doesn't prevent you from adding or changing elements of arrays or properties of objects.

You can do this:

const mogwai  = {}

mogwai.name = 'Gizmo';

Cannot do this:

const mogwai = {}

mogwai = { name: 'Gizmo' }

Unique Keys

It just makes sense that keys ought to be unique within an object. Values, however, can be whatever.

An object can not have more than one key with the same name. If it does, the value will default to the last key with the same name, and the prior properties will be excluded on creation.

const borough = {
	name: "Brooklyn",
	name: "The Bronx"
}
console.log(borough);

=> Object { name: "The Bronx" }

Conclusion: keys should be unique within an object. Values, however, are not unique.

Use object properties with conditionals

You can use object properties with conditionals, loops, etc

const obj = {
	salutation: 'hi',
	count:4
}
if (obj.salutation === "hi") {
	console.log('ok');
}

for (let i = 0; i < obj.count; i++) {
	console.log(i);
}

You can test to see if a property exists on an object:

const obj = {
	something:'wuttt'
}

if (obj.something) {
	console.log('ok');
}
if (obj.anotherthing){
	console.log('ok');
} else {
	console.log('no go i dont have that property');
}

This is because accessing a property that doesn't exist on an object gives you undefined which is treated as false.

Section 2

Intro to JavaScript Classes





Learning Objectives

Students will be able to:

  • Describe the use case for classes
  • Describe encapsulation in OOP
  • Define a class
  • Instantiate a class
  • Include and use a constructor method in a class
  • Define prototype (instance) methods in a class
  • Recognize constructor functions (predecessor to classes)
  • Define static (class) methods
  • Use extends to create a subclass
  • Use super within a subclass




Lesson Setup

For this lesson, we're going to code along using a JavaScript REPL from repl.it -- you can name it "JavaScript Classes Practice".




What Are Classes?

  • In object oriented programming (OOP), we use objects to model our application's purpose.
  • Classes (as well as their predecessor, constructor functions) are used to create objects.
  • Think of classes as the blueprints used to create objects of a certain "type"...



Why Use Classes?

  • We've already been creating JS objects using object ___ notation.
  • So why do we need classes and/or constructor functions?
  • Because the number of a certain type of object needed by an application often varies at runtime; and...
  • Classes/constructors provide a convenient way to dynamically create objects as needed.



Encapsulation in OOP

  • Encapsulation is a key principle of Object Oriented Programming.
  • Encapsulation is the concept of bundling data (properties/attributes) and related behavior (methods) within an object.
  • Here comes a graphic depicting this principle...
  • Here's a code example of encapsulating data (attributes/properties) & behavior (methods):
const cohort = {
  id: 'SEIR Flex Madeline',
  students: ['Diana', 'Julio', 'Cory'],
  instructors: ['Arthur', 'Nando', 'Teo', 'Sean'],
  addStudent: function(name) {
    name = name[0].toUpperCase() + name.substr(1).toLowerCase();
    this.students.push(name);
  },
  pickRandomStudent: function() {
    const rndIdx = Math.floor(Math.random() * this.students.length);
    return this.students[rndIdx];
  }
};




Review Questions

❓ What does the acronym OOP stand for?

❓ In your own words, describe why Classes exist in OOP.

❓ In your own words, describe the OOP principle known as encapsulation.




Defining Classes in JS

Here's a minimal class definition that's good for nothing but creating empty objects:

class Vehicle {
 // Code to define the class's properties and methods
}

Looks similar to defining a function because classes are in fact, special functions, except...



❓ What's different compared to a function?

❓ What's different about the naming convention?






Instantiating a Class

Here's a bit more OOP vocab for you:

  • instance: An object created by a class
  • instantiate: We instantiate a class to create an object
  • instantiation: The process of creating an object

In JS, we create objects using the new keyword when invoking (instantiating) the class:

const v1 = new Vehicle();



The constructor Method

*When a class is being instantiated, the special constructor method in the class will automatically be called:*

class Vehicle {
	constructor(vin, make) {
		this.vin = vin;
		this.make = make;
	// return is not needed
	// because the new object is returned by default
	}
}

const plane = new Vehicle('X123Y', 'Boeing');
  • The purpose of the constructor method is to initialize the data properties of the new object being created (represented by this).
  • If there are no properties to initialize, the constructor method is optional (a hidden default constructor is called).



💪 Practice - Add a Property

Modify the Vehicle class by adding an additional property named model.

Test it out by instantiating another object like this:

const car = new Vehicle('A1234', 'Toyota', 'Camry');




Object Instantiation

When we invoke the class prefaced with the new keyword, behind the scenes:

  • JS creates a shiny new object (empty) and assigns it to the this keyword.
  • The constructor method is called with the arguments we provided when invoking the class. Remember, the constructor method is where we create/initialize properties on the new object assigned to this.
  • After the constructor is finished executing, the class automatically returns the shiny new object.
  • Although the constructor method is special because it's called automatically, there's nothing special about how it's defined, other methods are defined the same way...



Defining Methods in a Class

There are two types of methods that can be added to a class:

  • Prototype (instance) methods
  • Static (class) methods

Prototype methods are the most common and are available to be called by any instance of the class.What's an instance? for example when you use Array.prototype.forEach, you can only use that method on an instance of an Array like

const nums = [1,2,3]
nums.forEach((num)=>{
  console.log(num)
})

Static methods are methods that are called on the class itself and cannot be called by instances. For example when you use Math.random you don't need to create an instance of Math first.

console.log(Math.random());


Let's add a start method to our Vehicle class:

class Vehicle {
	// the constructor will always be called
	constructor(vin, make, model) {
		this.vin = vin;
		this.make = make;
		this.model = model;
		this.running = false;  // default to false
	}
	start() {
		this.running = true;
		console.log('running...');
	}
}

Note that unlike within object literals, methods are not separated by a comma.






💪 Practice - Defining Methods

Define a stop method that sets the running property to false and console.logs the message "stopped..."




Overriding Methods

Thanks to another OOP principle called inheritance, subclasses inherit methods from their parent classes.

  • JS is different from class-based languages like Java or Python in that its inheritance implementation is prototype-based.
    We won't go into prototypes during this lesson, but if you want to learn more, check out the docs here.


In JS, virtually every object inherits from the Object class and thus inherits it's methods, such as toString:

car.toString() // outputs something like '[object Object]'

If we define a method that already exists in the object hierarchy, we "override" it. For example, we can override the Object's toString method by adding it to our class:

 // existing methods above

 toString() {
   return 'Vehicle (' + this.vin + ') is a ' +
     this.make + ' model ' + this.model;
 }


Test it out.




Review Questions

You've just learned how to define a class and add prototype methods to it. This represents about 80% there is to know about classes - congrats!


Some questions before moving on:

❓ What is the JS keyword used to define a class?

❓ What is the name of the method in a class that is automatically called when we instantiate a class?

❓ What is the main purpose of this method?

❓ What character(s) separate the methods in a class definition?




Copyright © Per Scholas 2023