Object, Prototype, Arrays and Classes

\title{ Objects, Prototypes, Arrays, and Classes }

{Table of Contents}

Section One: JavaScript Objects

  • Introduction to JavaScript Objects

  • Types of JavaScript Objects

  • Accessing JavaScript Object Properties

  • Accessing JavaScript Object Values

  • Deleting Object Properties

  • Objects in Real Life

Object Methods

  • Creating a JavaScript Object

The Prototype Property

  • Object Prototypes in JavaScript

{Section Two: Built-in Objects}

  • Built-in Objects

  • Date

  • Number

  • Math Section Three: Arrays and Iteration JavaScript Arrays

$>\quad$ Reading and Writing Array Elements

  • Creating an Array

  • Arrays of Objects and Multidimensional Arrays

$>\quad$ Array Properties: Length

  • Array Methods

  • Iterating Arrays

$>\quad$ Javascript for...in Loop

{Section Four: JavaScript Classes}

Defining Classes

Class Methods

$>\quad$ Static Methods and Fields

$>\quad$ Private Class Features

$>\quad$ Class Inheritance

{Learning Objectives}

This lesson provides information on JavaScript objects, object prototypes, arrays, and classes. By the end of this lesson, learners will be able to:

  • Create JavaScript objects.

  • Access, modify, and delete JavaScript object properties.

  • Use JavaScript object methods.

  • Use the JavaScript object prototype to add properties to multiple objects at once.

  • Use the standard built-in JavaScript objects Date, Number, and Math.

  • Define arrays in JavaScript.

  • Manipulate arrays using Array object methods.

  • Iterate through arrays and objects using for loops.

  • Create a JavaScript class with a constructor, getters, setters, methods, static features, encapsulation, and inheritance.

{Section 1 \ JavaScript Objects}

{Introduction to JavaScript Objects}

A JavaScript object is a non-primitive data type that allows you to store multiple collections of data or JavaScript's fundamental data types. JavaScript objects are dynamic. Except for primitive data types, all JavaScript values are objects.

If you are familiar with other programming languages, JavaScript objects are a bit different. You do not need to create classes in order to create objects (but you have the option of doing so).

An object is an unordered collection of key:value pairs. Each key:value pair is called a property.

Properties can be added and deleted. The key of a property can be a string, and the value of a property can be any valid JavaScript value (e.g., a string, a number, an array, and even a function).

{Introduction to JavaScript Objects (continued)}

Variables in JavaScript can contain single values, as shown below.

Objects are variables too, but objects can contain many values. The values are written as key:value pairs (separated by a colon), such as:

\begin{tabular}{|l|l|} \hline Property & Value \ \hline firstName & John \ \hline lastName & Doe \ \hline age & 50 \ \hline eyeColor & blue \ \hline \end{tabular}

This syntax is also used independently of JavaScript as a text-based data format called JavaScript Object Notation (JSON), which you will see often when programming.

{Types of JavaScript Objects}

Any value in JavaScript that is not a string, number, boolean, null, or is undefined is an object because they are primitive data types. Other examples of objects include:

  • Booleans can be objects (if defined with the new keyword).

  • Numbers can be objects (if defined with the new keyword).

  • Strings can be objects (if defined with the new keyword).

  • Dates are always objects.

  • Maths are always objects.

  • Regular expressions are always objects.

  • Arrays are always objects.

  • Functions are always objects.

  • Objects are always objects.

Note: A primitive value is a value that has no properties or methods.

{Accessing JavaScript Object Properties}

There are three methods for accessing a property of an object: objectName.propertyName // e.g. person.age objectName["propertyName"] // e.g. person["age"] objectName[expression] $\quad / /$ e.g. $x=$ "age"; person $[x]$

Using the person example from previous slides:

{Accessing JavaScript Object Values}

Any JavaScript object can be converted to an array using Object.values(). The object.values ( ) method takes the object as an argument and returns an array with all of the object's values. It is important to note that the value array loses the context of the keys from the object.

We will discuss arrays in more detail later in the presentation.

{Deleting Object Properties}

The delete keyword deletes a property from an object but not the object itself.

{Objects in Real Life}

Objects in JavaScript (and other programming languages) become easier to understand if we relate them to objects in real life. For example:

  • A car is an object.

A car has properties, such as make, model, weight, and color.

  • All cars have the same properties, but the property values differ from car to car.

  • A car has methods, such as start, drive, brake, and stop.

  • All cars have the same methods, but the methods are performed at different times.

\begin{tabular}{|l|l|l|} \hline Object & Properties & Methods \ car.start() \ car.name = Fiat & car.model $=500$ & cave() \ & car.weight = $850 \mathrm{~kg}$ & car.brake() \ & car.color = white & car.stop() \ \hline \end{tabular}

{Object Methods}

Objects can also have methods, such as function definitions, which are stored in properties. Methods are actions that can be performed on objects and their properties.

For example, using our previous person object, we can have a method that returns their full name using the information already available in the firstName and lastName properties by making use of the this keyword:

We will discuss more about object methods and the this keyword later in this presentation.

{Creating a JavaScript Object}

With JavaScript, we can define and create our own objects in three ways:

  1. Define and create a single object by using an object literal.

  2. Define and create a single object with the keyword new.

  3. Define an object constructor, and then create objects of the constructed type using the keyword new.

We will go into detail about these three options in the following slides.

{Creating Objects: Literals}

The easiest way to create an object is to include an object literal in your JavaScript code. An object literal is a comma-separated list of colon-separated names or value pairs enclosed in curly braces.

A property name is a JavaScript identifier or a string literal (the empty string is allowed). A property value is any JavaScript expression. The value of the expression (it may be a primitive value or an object value) becomes the value of the property.

We can also add a new property to an object, even if its key does not currently exist within the object:

{Creating Objects: Literals (continued)}

Here are more examples of creating objects with object literals.

{Creating Objects: new Keyword}

When declaring variables, the best practice is to set an initial value as a starting point and let JavaScript know the type of the variable. Alternatively, you can use new keyword to declare a variable and assign it a type:

The Math object is not in the list. Math is a global object. The new keyword cannot be used on Math.

The new keyword creates a copy of the object and assigns the new copy to your variable. This copy would already have initial values for its properties: 0 for numbers, empty quotes for String, false for Boolean, and other default values depending on the object.

{Creating Objects: new Keyword (continued)}

The new keyword creates and initializes a new object. The new keyword must be followed by a function invocation. A function used in this way is called a constructor and serves to initialize a newly created object. Core JavaScript includes built-in constructors for native data types.

{Creating Objects: Object Constructors}

Sometimes, we need a "blueprint" for creating many objects of the same type. The way to create an object type is to use an object constructor function.

To do so, create a function that takes parameters. These parameters can be assigned to an object created by the function using the this keyword.

In JavaScript, the this keyword is the object that "owns" the code. The value of this, when used in an object, is the object itself. In a constructor function, this does not have a value; it is a substitute for the new object. The value of this will become the new object when a new object is created.

Once we have defined our object constructor function, we can create new objects from it by using the new keyword, calling the function with arguments passed into it, and assigning it to a variable. This allows us to quickly create multiple complex objects of the same type in a short period of time.

An example of this is on the following slide.

{Creating Objects: Object Constructors}

Here is an example of using object constructors:

{Adding Properties to Object Constructors}

Let's look at what happens when we attempt to add a property to our constructor function after it has been defined:

Notice that the species property is undefined. In order to add properties to existing objects like this, we need to use object prototypes. We will discuss prototypes on the following slides.

{The Prototype Property}

Sometimes, we need to add new properties (or methods) to all existing objects of a given type or object constructor. The JavaScript prototype property allows you to add new properties to the existing objects and object constructors.

Let's take the previous example and try to use prototype for adding a new property for species.

It works! We will discuss the details of what exactly prototype is and how it works next.

{Object Prototypes in JavaScript}

Object prototypes are the mechanism by which JavaScript objects inherit features from one another. Objects that are created from the same object have the same properties and methods.

Every JavaScript object has a prototype object associated with it and inherits properties from the prototype. You can see this with the developer tool as shown to the right.

  • The object.prototype is on the top of the prototype inheritance chain.

Date objects inherit from Date.prototype. Array objects inherit from Array. prototype.

Person objects inherit from Person. prototype. Date objects, Array objects, and Person objects inherit from object. prototype.

{Object Prototypes in JavaScript (continued)}

To find the species property from our previous example, shown again below, we would need to expand the prototype object's proto property. However, as we have seen in our previous example, you can access the new property directly from the source object: myFather . species. Why is this?

While species is inside the prototype object, JavaScript first checks if it is part of the myFather object. If it cannot find the property within the object being referenced, it then checks that object's prototype. This is true for all objects in JavaScript.

{Object Prototypes in JavaScript (continued)}

You can also use prototypes to apply a new property to all objects of a given type even after those objects have been created. If you have already specified a property by that name for an individual object, the prototype property will not overwrite it, but will be accessible. For example:

{Object Prototypes in JavaScript (continued)}

While, in practice, all browsers use the proto property to point to an objects prototype, this is not a standard implementation and could break even if it is unlikely to. The standard for accessing an object's prototype is to use the object. getPrototypeof() method, as follows:

{Knowledge Check}

  • How do objects in JavaScript store data?

  • What is the syntax for creating an object literal?

  • What are two of the primitive data types (data that is not an object) in JavaScript?

  • What are two ways to access object properties?

  • What is the method for accessing all values of an object?

  • What is the keyword for deleting object properties?

  • How do you create an object constructor?

  • How do you create new objects from a constructor once the constructor has been defined?

  • How can you use the Prototype object to add properties to already existing objects?

{Section 2 \ Built-in Objects}

{Built-in Objects}

JavaScript provides a number of standard built-in objects (also known as "global objects") that include useful properties and methods for common tasks. In the following slides, we will detail a few of the most commonly used built-in objects:

Date - Used for creating and manipulating dates in a standard format.

  • Number - Contains constants and methods for working with numbers.

Math - Includes properties and methods for mathematical constants and functions.

{Built-in Objects: Date}

Date objects are created with the new Date() constructor. By default, JavaScript will use the browser's time zone, and display a date as a full text string. There are four ways to create a Date:

Date objects are static. Even though computer time is ticking alongside real time, Date objects do not automatically increment their values.

{Built-in Objects: Date - Examples}

Here are some examples of Date objects being created.

{Built-in Objects: Date - Manipulation}

Once a Date object is created, several methods allow you to operate on it. Most methods simply allow you to get and set the year, month, day, hour, minute, second, and millisecond fields of the object.

A full list of Date methods can be found in this reference, but here are a few examples in use:

{Built-in Objects: Number}

The JavaScript Number object is a wrapper object, allowing you to work with numerical values. A Number object is created using the Number() constructor, which also attempts to convert non-number data types into numbers. For example:

The typeof keyword returns the type of the value right in front of it. The typeof keyword is one of the few function-like objects that does not require parentheses.

The Number object also has many other useful properties and methods, described in the documentation linked above. For example, this method formats numbers into exponential notation:

console. $\log ($ Number(340900000000000000).toExponential()); // $3.409 e+17$

{Built-in Objects: Math}

The JavaScript Math object provides you properties and methods for mathematical constants and functions. Unlike other global objects, Math has no constructors. All of the properties and methods of Math are static and can be called by using Math as an object without creating it.

{Built-in Objects: Math.random()}

One of the frequently-used methods of the Math object is Math.random(). Math.random() returns a random number between $\theta$ (inclusive), and 1 (exclusive), which means it always returns a number lower than 1.

When combined with other methods and operators, Math.random() can be used to return values with specific properties, such as a range of inclusive integers. For instance:

{Built-in Objects: Math.random() - Examples}

Let's analyze the previous example:

  • Math.floor(Math. random( $) *(x+1))$ returns a value from $\theta$ to $x$ (inclusive), because Math.floor() always rounds down and Math. random() never returns 1 .

  • Math.floor(Math. random ()$+\mathbf{x}$ ) returns $\mathbf{x}$, effectively shifting the lowest value that can be returned when Math. random() is paired with Math.floor().

Combining these two concepts, the full expression above gives us a range of integers with the same difference between their min and max values as between our min and max constants, and then that entire range is shifted to match our given minimum.

{Built-in Objects: Math.random() - Examples}

If generating random whole numbers within a range of two values is going to be something we do often, we should create a function to simplify our code:

Now, we can easily use this logic anywhere!

{Practice Activity: Math.random()}

Modify this script so that every time the user enters their guess, the program updates the range. The range should narrow as the user guesses.

{For example:}

Guess a number between 1 and 10: 3

Guess a number between 4 and 10: 5

You got it: 5

{Practice Activity: Math.random() - Solution}

Your solution may be different than the one below, but if it works, great!

{Section 3 \ Arrays and Iteration}

{JavaScript Arrays}

An Array object is a standard built-in object in JavaScript. It is an ordered collection of values, or a special variable, which can hold more than one value at a time. Each value is called an element, and each element has a numeric position in the array, known as its index.

JavaScript arrays are untyped: an array element may be of any type, and different elements of the same array may be of different types.

JavaScript array indices are zero-based and use 32-bit indices: The index of the first element is 0, and the highest possible index is 4294967294 , for a maximum array size of $4,294,967,295$ elements.

  • JavaScript arrays are dynamic: They grow or shrink as needed, and there is no need to declare a fixed size for the array when you create it (or to reallocate it when the size changes).

Arrays are created, typically, using square-brackets and a comma-separated list of elements. We will go into more detail on the creation of arrays later.

{Reading and Writing Array Elements}

To access an Array element, you need to specify the name of the Array, followed by square brackets, and then place the index of the elements within the brackets. Array indexes start counting from $\boldsymbol{\theta}$. For example, an array of size ten would have its index go from $\boldsymbol{\theta}$ to 9 (inclusive).

Array elements can be read or written this way. If there is no element at the given index, or that element is empty, it will produce a result of undefined.

For example:

{Creating an Array}

There are many ways to declare an array, the simplest of which is by using square bracket syntax with a comma-separated list of elements within:

Array elements can also be initialized with variables:

An alternative to square-bracket syntax is using the Array constructor with the new keyword:

Note: When creating a new Array via the Array Constructor, a single numeric argument will result in an array of the argument's length with undefined elements. To explicitly create an Array with the constructor, the arguments must be two or more elements, or a single non-numeric element.

{Arrays of Objects and Multidimensional Arrays}

Arrays can also contain objects as elements, and accessing the values of those objects within the Array requires combining Array-access syntax with Object-access syntax:

Arrays can also be multi-dimensional, which means that they can contain other arrays (which can contain other arrays, and so on):

{Developer Tools Experimentation}

Take a few minutes to try the different ways to create an array using the developer tools in the Chrome browser.

{Array Properties: Length}

Every array has a length property, and it is this property that makes arrays different from regular JavaScript objects. For arrays that are dense (i.e., not sparse), the length property specifies the number of elements in the array. Its value is one more than the highest index in the array: []. length; // no elements, length is $\theta$ [2, 3, 5, 7, 11].length; // five elements, length is 5, highest index is 4

You can also modify the length of the array using the length property:

Notice how assigning an array a length that is larger than its current length adds undefined elements to the end of the array. Likewise, when you shorten an array by assigning a length that is smaller than its current length, elements on the end are lost (forever, unless you stored them elsewhere first).

{Array Methods in JavaScript}

JavaScript provides many useful methods for Array objects, some of which we will discuss in more detail in the following slides. Here us a list of some of the most common Array methods:

  • length( $)$ - Returns the number of elements in an array.

  • reverse( ) - Returns the array in reverse order.

$>\operatorname{sort}()-$ Sorts the elements of an array in specific order.

  • join( ) - Concatenates the array elements to a string.

  • tostring( ) - Returns the string representation of an array.

$>\operatorname{pop}()$ - Removes and returns the last array element.

$>\operatorname{push}()$ - Adds elements to end of array and returns its length.

splice()-Returns an array by changing its elements in place.

  • slice() - Returns a shallow copy of a portion of an array.

{Array Methods: Push, Pop, and Shift}

We have already seen how to add new elements to an array via square-bracket notation, as follows:

Elements can also be added to an array by using the push() method. This method adds one or more elements to the end of an array, and returns a value equal to the new length of the array. For example:

To remove an element from an array, you can use the pop() and shift() methods. The pop() method removes the last element from an array and returns that element. The shift() method removes and returns the first element of the array.

{Array Methods: Join}

The Array.join() method converts all of the elements of an array to strings and concatenates them, returning the resulting string. You can specify an optional string that separates the elements in the resulting string. If no separator string is specified, a comma is used.

For example:

The String.split() method does the opposite by taking a string and dividing it into an array of substrings based on a given delimiter.

const $c=x . s p l i t(", ") ; \quad / /\left[{ }^{\prime} 1^{\prime},{ }^{\prime} 2^{\prime},{ }^{\prime} 3^{\prime}\right]$

{Array Methods: Reverse}

The Array. reverse() method reverses the order of the elements of an array and returns the reversed array. It does this in place, which means that it does not create a new array with the elements rearranged, but instead rearranges them in the already existing array.

The following code, which uses the reverse() and join() methods, produces the string “3, 2, 1 ":

{Array Methods: Sort}

Array.sort() sorts the elements of an array in place and returns the sorted array. When sort ( ) is called with no arguments, it sorts the array elements in alphabetical order.

For example:

{Array Methods: Slice}

The Array.slice() method returns a slice (or subarray), of the specified array. The returned array contains the element specified by the first argument and all subsequent elements, up to, but not including, the element specified by the second argument.

The slice(start, end) method takes:

start (optional) - Starting index of the selection. If not provided, the selection starts at the beginning of the array

end (optional) - Ending index of the selection (exclusive). If not provided, the selection ends at the index of the last element.

If only one argument is specified, the returned array contains all elements from the start position to the end of the array. You can also use negative start and end indices. The index of the last element is -1 , the index of the second last element is -2 , and so on.

{Array Methods: Slice - Examples}

Note that slice() does not modify the array on which it is invoked. Here are some examples:

{Array Methods: Splice}

The splice() method can delete elements from an array, insert new elements into an array, or perform both operations at the same time. Elements of the array that come after the insertion or deletion point have their indexes increased or decreased as necessary so that they remain contiguous with the rest of the array.

While splice() and slice() have similar names, they perform very different operations in very different ways. It is important to note that splice() does modify the original array in place.

For example:

The first parameter (2) defines where new elements should be spliced in. The second parameter $(\theta)$ defines how many elements should be removed.

The remainder of the parameters ("lemon", "kiwi") define the new elements to be added.

The splice() method returns an array with any deleted items.

{Array Methods: Splice - Examples}

Here are some more examples of the splice() method in use:

{Iterating Arrays}

Using a for loop, we can access each element in an array as long as we make the range of the for loop dependent on the array's length property.

Notice that in the example below (and in all implementations that iterate through an entire array) the index goes up to the array's length minus one (using <, not $<=$ ) because the index starts from 0.

let $a=[23,32,45,67,77,67,98,12]$;

for (let $i=0 ; i<a$. length; $i++$ )

console. $\log (a[i]) ; / /$ will output each element of the array 子

Instead of console. $\log ()$ to simply print the elements, you can include any logic or manipulation your particular solution requires.

{JavaScript for...in Loop}

The JavaScript for... in statement loops through the properties of an object, which can be an array or any other iterable object. For instance, the array iteration example from the previous slide could also be executed as follows:

However, it is not a best practice to use for...in statements to iterate over arrays. This is because the for... in statement will iterate over user-defined properties in addition to numeric indexes if you modify the Array object (such as adding properties or methods). Therefore, you should continue to use traditional for loops to iterate through arrays.

We will talk about the usefulness of for...in with other object types on the next slide.

{JavaScript for...in Loop (continued)}

Using the for...in statement to iterate over the elements of a key:value pair object, such as those discussed earlier in this lesson, provides us with a clean and efficient way to access object keys and their associated values.

For example:

It is important to note that person. personKey would not work in this context because personKey is a variable. The person. personKey statement would attempt to access the value at key "personKey."

{Knowledge Check}

What is the index of the first element in an array?

  • How would you create an array with 10,000 empty (undefined) elements in a single line of code?

  • How do you access the elements of a multidimensional array?

  • How do you access the elements of an object within an array?

  • What array method adds elements to the end of an existing array?

  • Which array methods remove elements from an existing array? Which method removes from the start of the array, and which removes from the end?

  • What does the Array.join() method do?

  • What is the default sorting option for the Array. sort () method?

  • What are the differences between Array.slice() and Array.splice()?

  • When using a for loop to iterate through an array, what is the value of the final index in the loop relative to the array's length?

  • How do you use a for...in loop to iterate through an object's values?

{Section 4 \ JavaScript Classes}

{Defining Classes}

JavaScript classes are templates for creating objects that are used to encapsulate data. They are similar to objects and object prototypes, but have some unique syntax and properties. The class keyword indicates that a class is being defined, and the class's body is enclosed in curly braces.

Classes can be defined in two ways - a class expression, or a class declaration. The following is an example of a class declaration:

It is important to note that the body of a class is always executed in strict mode.

{Class Methods}

The constructor method is used for creating and initializing an object created with the class. There can only be one instance of a constructor method per class.

The get and set keywords bind object properties to a function that will be called when those properties are looked up or modified. An example of this is to the right.

Having getters and setters is one of the advantages of classes, because you can control the behavior of each separately.

Other methods can be created and implemented for whatever purpose your class needs.

{Static Methods and Fields}

The static keyword denotes properties and methods that are defined within the class itself, not the instances of the class.

Static methods are often used to create utility functions that perform actions that are independent of the state of an individual object. Static properties or fields are useful for caches, fixed-configuration values, or any other data that does not need to be replicated across each instance of the class's objects.

For readability, the get and set methods from the previous slide have been removed from the example, but if you're following along you may keep them within your code.

{Private Class Features}

Fields can be made private by adding a # symbol to the beginning of the field's declaration. Private fields cannot be accessed from outside of the class's body.

Private fields must be declared up front; they cannot be created later through assigning to them in the way that normal properties can.

This is a way to encapsulate the state variables of an object so that users can only access those values in the ways declared by your getters and setters.

Notice that when we attempt to access firstName and lastName in the example, it returns undefined.

{Class Inheritance}

Inheritance refers to the ability of one class to take on all of the properties of another class via the extends keyword.

The extends keyword is used in class declarations or expressions to create a class as a child of another class. For example, all learners are persons, but learners have specific properties that not all persons have.

The super keyword can be used to explicitly call methods of the parent class from within the child class.

Since the child class inherits all properties of the parent class, we can create a new Learner the same way we created a Person previously.

{PA - Objects and Classes}

Please follow the link below to the practice assignment for objects and classes.

  • PA-308.3.1 - Objects and Classes

  • You can also find this assignment on Canvas under the Assignments section.

  • If you have technical questions while performing the activity, ask your instructors for assistance.

{Summary}

  • A JavaScript object is a non-primitive data type that allows you to store multiple unordered collections of data. Objects store data in key:value pairs.

JavaScript provides standard built-in objects (global objects) such as Date, Number, and Math, that have many useful properties and methods for commonly encountered tasks.

  • Arrays are useful for storing ordered collections of data when descriptive keys are unnecessary.

  • Arrays do have a few named properties, such as length.

  • The Array object provides many useful methods for working with arrays, such as pop, push, shift, slice, splice, join, sort, and reverse.

  • Both arrays and objects can be iterated through using for loops.

  • Classes are templates for creating objects, and have unique syntax and properties that differentiate them from standard objects and object prototypes.

  • Classes can define separate methods for accessing or modifying the same piece of data, and can encapsulate data to prevent users from modifying it improperly.

Classes can also extend other classes and inherit their properties, fields, and methods.

{Questions?}

Last updated