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.
![](https://peterlulu666.gitbook.io/~gitbook/image?url=https%3A%2F%2Fcdn.mathpix.com%2Fcropped%2F2023_06_18_3e182b40eb809e86a4a2g-06.jpg%3Fheight%3D140%26width%3D701%26top_left_y%3D429%26top_left_x%3D300&width=768&dpr=4&quality=100&sign=6d3e7828&sv=1)
Objects are variables too, but objects can contain many values. The values are written as key:value pairs (separated by a colon), such as:
![](https://peterlulu666.gitbook.io/~gitbook/image?url=https%3A%2F%2Fcdn.mathpix.com%2Fcropped%2F2023_06_18_3e182b40eb809e86a4a2g-06.jpg%3Fheight%3D394%26width%3D659%26top_left_y%3D730%26top_left_x%3D298&width=768&dpr=4&quality=100&sign=c54383e&sv=1)
\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:
![](https://peterlulu666.gitbook.io/~gitbook/image?url=https%3A%2F%2Fcdn.mathpix.com%2Fcropped%2F2023_06_18_3e182b40eb809e86a4a2g-08.jpg%3Fheight%3D526%26width%3D2052%26top_left_y%3D794%26top_left_x%3D285&width=768&dpr=4&quality=100&sign=b967ded0&sv=1)
{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.
![](https://peterlulu666.gitbook.io/~gitbook/image?url=https%3A%2F%2Fcdn.mathpix.com%2Fcropped%2F2023_06_18_3e182b40eb809e86a4a2g-09.jpg%3Fheight%3D582%26width%3D1404%26top_left_y%3D684%26top_left_x%3D292&width=768&dpr=4&quality=100&sign=247a819&sv=1)
{Deleting Object Properties}
The delete keyword deletes a property from an object but not the object itself.
![](https://peterlulu666.gitbook.io/~gitbook/image?url=https%3A%2F%2Fcdn.mathpix.com%2Fcropped%2F2023_06_18_3e182b40eb809e86a4a2g-10.jpg%3Fheight%3D697%26width%3D1709%26top_left_y%3D451%26top_left_x%3D268&width=768&dpr=4&quality=100&sign=30db4ff1&sv=1)
{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:
![](https://peterlulu666.gitbook.io/~gitbook/image?url=https%3A%2F%2Fcdn.mathpix.com%2Fcropped%2F2023_06_18_3e182b40eb809e86a4a2g-12.jpg%3Fheight%3D544%26width%3D1448%26top_left_y%3D660%26top_left_x%3D292&width=768&dpr=4&quality=100&sign=2a212491&sv=1)
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:
Define and create a single object by using an object literal.
Define and create a single object with the keyword new.
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:
![](https://peterlulu666.gitbook.io/~gitbook/image?url=https%3A%2F%2Fcdn.mathpix.com%2Fcropped%2F2023_06_18_3e182b40eb809e86a4a2g-14.jpg%3Fheight%3D448%26width%3D1225%26top_left_y%3D880%26top_left_x%3D274&width=768&dpr=4&quality=100&sign=46149265&sv=1)
{Creating Objects: Literals (continued)}
Here are more examples of creating objects with object literals.
![](https://peterlulu666.gitbook.io/~gitbook/image?url=https%3A%2F%2Fcdn.mathpix.com%2Fcropped%2F2023_06_18_3e182b40eb809e86a4a2g-15.jpg%3Fheight%3D837%26width%3D2036%26top_left_y%3D462%26top_left_x%3D266&width=768&dpr=4&quality=100&sign=f324ebec&sv=1)
{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:
![](https://peterlulu666.gitbook.io/~gitbook/image?url=https%3A%2F%2Fcdn.mathpix.com%2Fcropped%2F2023_06_18_3e182b40eb809e86a4a2g-16.jpg%3Fheight%3D481%26width%3D1413%26top_left_y%3D555%26top_left_x%3D275&width=768&dpr=4&quality=100&sign=50859e95&sv=1)
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.
![](https://peterlulu666.gitbook.io/~gitbook/image?url=https%3A%2F%2Fcdn.mathpix.com%2Fcropped%2F2023_06_18_3e182b40eb809e86a4a2g-17.jpg%3Fheight%3D390%26width%3D2029%26top_left_y%3D547%26top_left_x%3D271&width=768&dpr=4&quality=100&sign=50683332&sv=1)
{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:
![](https://peterlulu666.gitbook.io/~gitbook/image?url=https%3A%2F%2Fcdn.mathpix.com%2Fcropped%2F2023_06_18_3e182b40eb809e86a4a2g-19.jpg%3Fheight%3D819%26width%3D2056%26top_left_y%3D421%26top_left_x%3D271&width=768&dpr=4&quality=100&sign=930efcb7&sv=1)
{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:
![](https://peterlulu666.gitbook.io/~gitbook/image?url=https%3A%2F%2Fcdn.mathpix.com%2Fcropped%2F2023_06_18_3e182b40eb809e86a4a2g-20.jpg%3Fheight%3D652%26width%3D1598%26top_left_y%3D502%26top_left_x%3D269&width=768&dpr=4&quality=100&sign=aef77ee9&sv=1)
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.
![](https://peterlulu666.gitbook.io/~gitbook/image?url=https%3A%2F%2Fcdn.mathpix.com%2Fcropped%2F2023_06_18_3e182b40eb809e86a4a2g-21.jpg%3Fheight%3D533%26width%3D1597%26top_left_y%3D656%26top_left_x%3D271&width=768&dpr=4&quality=100&sign=3208a848&sv=1)
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.
![](https://peterlulu666.gitbook.io/~gitbook/image?url=https%3A%2F%2Fcdn.mathpix.com%2Fcropped%2F2023_06_18_3e182b40eb809e86a4a2g-22.jpg%3Fheight%3D631%26width%3D871%26top_left_y%3D692%26top_left_x%3D1427&width=768&dpr=4&quality=100&sign=8273f3ee&sv=1)
{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?
![](https://peterlulu666.gitbook.io/~gitbook/image?url=https%3A%2F%2Fcdn.mathpix.com%2Fcropped%2F2023_06_18_3e182b40eb809e86a4a2g-23.jpg%3Fheight%3D478%26width%3D1498%26top_left_y%3D603%26top_left_x%3D269&width=768&dpr=4&quality=100&sign=5fc2d1eb&sv=1)
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:
![](https://peterlulu666.gitbook.io/~gitbook/image?url=https%3A%2F%2Fcdn.mathpix.com%2Fcropped%2F2023_06_18_3e182b40eb809e86a4a2g-24.jpg%3Fheight%3D715%26width%3D1493%26top_left_y%3D613%26top_left_x%3D249&width=768&dpr=4&quality=100&sign=658fda68&sv=1)
{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:
![](https://peterlulu666.gitbook.io/~gitbook/image?url=https%3A%2F%2Fcdn.mathpix.com%2Fcropped%2F2023_06_18_3e182b40eb809e86a4a2g-25.jpg%3Fheight%3D767%26width%3D1710%26top_left_y%3D540%26top_left_x%3D269&width=768&dpr=4&quality=100&sign=9fadbd2b&sv=1)
{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:
![](https://peterlulu666.gitbook.io/~gitbook/image?url=https%3A%2F%2Fcdn.mathpix.com%2Fcropped%2F2023_06_18_3e182b40eb809e86a4a2g-29.jpg%3Fheight%3D580%26width%3D2058%26top_left_y%3D555%26top_left_x%3D268&width=768&dpr=4&quality=100&sign=5cae0eeb&sv=1)
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.
![](https://peterlulu666.gitbook.io/~gitbook/image?url=https%3A%2F%2Fcdn.mathpix.com%2Fcropped%2F2023_06_18_3e182b40eb809e86a4a2g-30.jpg%3Fheight%3D865%26width%3D1296%26top_left_y%3D444%26top_left_x%3D273&width=768&dpr=4&quality=100&sign=58817bc7&sv=1)
{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:
![](https://peterlulu666.gitbook.io/~gitbook/image?url=https%3A%2F%2Fcdn.mathpix.com%2Fcropped%2F2023_06_18_3e182b40eb809e86a4a2g-31.jpg%3Fheight%3D456%26width%3D1823%26top_left_y%3D684%26top_left_x%3D273&width=768&dpr=4&quality=100&sign=a12e0f04&sv=1)
{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:
![](https://peterlulu666.gitbook.io/~gitbook/image?url=https%3A%2F%2Fcdn.mathpix.com%2Fcropped%2F2023_06_18_3e182b40eb809e86a4a2g-32.jpg%3Fheight%3D244%26width%3D1006%26top_left_y%3D566%26top_left_x%3D271&width=768&dpr=4&quality=100&sign=334cf106&sv=1)
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.
![](https://peterlulu666.gitbook.io/~gitbook/image?url=https%3A%2F%2Fcdn.mathpix.com%2Fcropped%2F2023_06_18_3e182b40eb809e86a4a2g-33.jpg%3Fheight%3D718%26width%3D2031%26top_left_y%3D562%26top_left_x%3D273&width=768&dpr=4&quality=100&sign=1dbd67c&sv=1)
{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:
![](https://peterlulu666.gitbook.io/~gitbook/image?url=https%3A%2F%2Fcdn.mathpix.com%2Fcropped%2F2023_06_18_3e182b40eb809e86a4a2g-34.jpg%3Fheight%3D430%26width%3D1790%26top_left_y%3D721%26top_left_x%3D289&width=768&dpr=4&quality=100&sign=957c1fb9&sv=1)
{Built-in Objects: Math.random() - Examples}
Let's analyze the previous example:
![](https://peterlulu666.gitbook.io/~gitbook/image?url=https%3A%2F%2Fcdn.mathpix.com%2Fcropped%2F2023_06_18_3e182b40eb809e86a4a2g-35.jpg%3Fheight%3D305%26width%3D1801%26top_left_y%3D434%26top_left_x%3D273&width=768&dpr=4&quality=100&sign=a4fc5b78&sv=1)
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:
![](https://peterlulu666.gitbook.io/~gitbook/image?url=https%3A%2F%2Fcdn.mathpix.com%2Fcropped%2F2023_06_18_3e182b40eb809e86a4a2g-36.jpg%3Fheight%3D542%26width%3D1988%26top_left_y%3D526%26top_left_x%3D271&width=768&dpr=4&quality=100&sign=c3d20a42&sv=1)
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
![](https://peterlulu666.gitbook.io/~gitbook/image?url=https%3A%2F%2Fcdn.mathpix.com%2Fcropped%2F2023_06_18_3e182b40eb809e86a4a2g-37.jpg%3Fheight%3D756%26width%3D1262%26top_left_y%3D540%26top_left_x%3D1110&width=768&dpr=4&quality=100&sign=1fc64982&sv=1)
{Practice Activity: Math.random() - Solution}
Your solution may be different than the one below, but if it works, great!
![](https://peterlulu666.gitbook.io/~gitbook/image?url=https%3A%2F%2Fcdn.mathpix.com%2Fcropped%2F2023_06_18_3e182b40eb809e86a4a2g-38.jpg%3Fheight%3D848%26width%3D1648%26top_left_y%3D440%26top_left_x%3D426&width=768&dpr=4&quality=100&sign=b627b93&sv=1)
{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:
![](https://peterlulu666.gitbook.io/~gitbook/image?url=https%3A%2F%2Fcdn.mathpix.com%2Fcropped%2F2023_06_18_3e182b40eb809e86a4a2g-41.jpg%3Fheight%3D458%26width%3D2084%26top_left_y%3D875%26top_left_x%3D269&width=768&dpr=4&quality=100&sign=d0a06d88&sv=1)
{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:
![](https://peterlulu666.gitbook.io/~gitbook/image?url=https%3A%2F%2Fcdn.mathpix.com%2Fcropped%2F2023_06_18_3e182b40eb809e86a4a2g-42.jpg%3Fheight%3D183%26width%3D1986%26top_left_y%3D485%26top_left_x%3D295&width=768&dpr=4&quality=100&sign=1ad43b24&sv=1)
Array elements can also be initialized with variables:
![](https://peterlulu666.gitbook.io/~gitbook/image?url=https%3A%2F%2Fcdn.mathpix.com%2Fcropped%2F2023_06_18_3e182b40eb809e86a4a2g-42.jpg%3Fheight%3D129%26width%3D1189%26top_left_y%3D740%26top_left_x%3D292&width=768&dpr=4&quality=100&sign=e2925352&sv=1)
An alternative to square-bracket syntax is using the Array constructor with the new keyword:
![](https://peterlulu666.gitbook.io/~gitbook/image?url=https%3A%2F%2Fcdn.mathpix.com%2Fcropped%2F2023_06_18_3e182b40eb809e86a4a2g-42.jpg%3Fheight%3D181%26width%3D1973%26top_left_y%3D935%26top_left_x%3D295&width=768&dpr=4&quality=100&sign=dc8ad27e&sv=1)
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:
![](https://peterlulu666.gitbook.io/~gitbook/image?url=https%3A%2F%2Fcdn.mathpix.com%2Fcropped%2F2023_06_18_3e182b40eb809e86a4a2g-43.jpg%3Fheight%3D197%26width%3D1465%26top_left_y%3D504%26top_left_x%3D273&width=768&dpr=4&quality=100&sign=ca84a8ec&sv=1)
Arrays can also be multi-dimensional, which means that they can contain other arrays (which can contain other arrays, and so on):
![](https://peterlulu666.gitbook.io/~gitbook/image?url=https%3A%2F%2Fcdn.mathpix.com%2Fcropped%2F2023_06_18_3e182b40eb809e86a4a2g-43.jpg%3Fheight%3D476%26width%3D1481%26top_left_y%3D837%26top_left_x%3D271&width=768&dpr=4&quality=100&sign=ee2730c7&sv=1)
{Developer Tools Experimentation}
Take a few minutes to try the different ways to create an array using the developer tools in the Chrome browser.
![](https://peterlulu666.gitbook.io/~gitbook/image?url=https%3A%2F%2Fcdn.mathpix.com%2Fcropped%2F2023_06_18_3e182b40eb809e86a4a2g-44.jpg%3Fheight%3D683%26width%3D1224%26top_left_y%3D561%26top_left_x%3D635&width=768&dpr=4&quality=100&sign=8fb310f3&sv=1)
{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:
![](https://peterlulu666.gitbook.io/~gitbook/image?url=https%3A%2F%2Fcdn.mathpix.com%2Fcropped%2F2023_06_18_3e182b40eb809e86a4a2g-45.jpg%3Fheight%3D188%26width%3D1908%26top_left_y%3D786%26top_left_x%3D273&width=768&dpr=4&quality=100&sign=2ae44374&sv=1)
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:
![](https://peterlulu666.gitbook.io/~gitbook/image?url=https%3A%2F%2Fcdn.mathpix.com%2Fcropped%2F2023_06_18_3e182b40eb809e86a4a2g-47.jpg%3Fheight%3D118%26width%3D1485%26top_left_y%3D452%26top_left_x%3D276&width=768&dpr=4&quality=100&sign=3f5b9bf2&sv=1)
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:
![](https://peterlulu666.gitbook.io/~gitbook/image?url=https%3A%2F%2Fcdn.mathpix.com%2Fcropped%2F2023_06_18_3e182b40eb809e86a4a2g-47.jpg%3Fheight%3D177%26width%3D1112%26top_left_y%3D723%26top_left_x%3D273&width=768&dpr=4&quality=100&sign=6590a784&sv=1)
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.
![](https://peterlulu666.gitbook.io/~gitbook/image?url=https%3A%2F%2Fcdn.mathpix.com%2Fcropped%2F2023_06_18_3e182b40eb809e86a4a2g-47.jpg%3Fheight%3D178%26width%3D1140%26top_left_y%3D1110%26top_left_x%3D275&width=768&dpr=4&quality=100&sign=3fb76ec9&sv=1)
{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:
![](https://peterlulu666.gitbook.io/~gitbook/image?url=https%3A%2F%2Fcdn.mathpix.com%2Fcropped%2F2023_06_18_3e182b40eb809e86a4a2g-48.jpg%3Fheight%3D392%26width%3D1928%26top_left_y%3D638%26top_left_x%3D273&width=768&dpr=4&quality=100&sign=eaceeb18&sv=1)
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 ":
![](https://peterlulu666.gitbook.io/~gitbook/image?url=https%3A%2F%2Fcdn.mathpix.com%2Fcropped%2F2023_06_18_3e182b40eb809e86a4a2g-49.jpg%3Fheight%3D265%26width%3D1875%26top_left_y%3D716%26top_left_x%3D271&width=768&dpr=4&quality=100&sign=8beca3be&sv=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:
![](https://peterlulu666.gitbook.io/~gitbook/image?url=https%3A%2F%2Fcdn.mathpix.com%2Fcropped%2F2023_06_18_3e182b40eb809e86a4a2g-50.jpg%3Fheight%3D484%26width%3D1816%26top_left_y%3D619%26top_left_x%3D290&width=768&dpr=4&quality=100&sign=d5e02c3b&sv=1)
{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:
![](https://peterlulu666.gitbook.io/~gitbook/image?url=https%3A%2F%2Fcdn.mathpix.com%2Fcropped%2F2023_06_18_3e182b40eb809e86a4a2g-52.jpg%3Fheight%3D859%26width%3D1707%26top_left_y%3D426%26top_left_x%3D262&width=768&dpr=4&quality=100&sign=8e9800fd&sv=1)
{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:
![](https://peterlulu666.gitbook.io/~gitbook/image?url=https%3A%2F%2Fcdn.mathpix.com%2Fcropped%2F2023_06_18_3e182b40eb809e86a4a2g-53.jpg%3Fheight%3D234%26width%3D1566%26top_left_y%3D778%26top_left_x%3D275&width=768&dpr=4&quality=100&sign=c9510c70&sv=1)
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:
![](https://peterlulu666.gitbook.io/~gitbook/image?url=https%3A%2F%2Fcdn.mathpix.com%2Fcropped%2F2023_06_18_3e182b40eb809e86a4a2g-54.jpg%3Fheight%3D705%26width%3D2082%26top_left_y%3D452%26top_left_x%3D273&width=768&dpr=4&quality=100&sign=dd0d2fc5&sv=1)
{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:
![](https://peterlulu666.gitbook.io/~gitbook/image?url=https%3A%2F%2Fcdn.mathpix.com%2Fcropped%2F2023_06_18_3e182b40eb809e86a4a2g-56.jpg%3Fheight%3D293%26width%3D1851%26top_left_y%3D550%26top_left_x%3D273&width=768&dpr=4&quality=100&sign=b9e03cfb&sv=1)
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:
![](https://peterlulu666.gitbook.io/~gitbook/image?url=https%3A%2F%2Fcdn.mathpix.com%2Fcropped%2F2023_06_18_3e182b40eb809e86a4a2g-57.jpg%3Fheight%3D532%26width%3D1549%26top_left_y%3D582%26top_left_x%3D291&width=768&dpr=4&quality=100&sign=dacf52af&sv=1)
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:
![](https://peterlulu666.gitbook.io/~gitbook/image?url=https%3A%2F%2Fcdn.mathpix.com%2Fcropped%2F2023_06_18_3e182b40eb809e86a4a2g-60.jpg%3Fheight%3D497%26width%3D1465%26top_left_y%3D737%26top_left_x%3D271&width=768&dpr=4&quality=100&sign=a1e9e2d8&sv=1)
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.
![](https://peterlulu666.gitbook.io/~gitbook/image?url=https%3A%2F%2Fcdn.mathpix.com%2Fcropped%2F2023_06_18_3e182b40eb809e86a4a2g-61.jpg%3Fheight%3D936%26width%3D1058%26top_left_y%3D366%26top_left_x%3D1264&width=768&dpr=4&quality=100&sign=7016a822&sv=1)
{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.
![](https://peterlulu666.gitbook.io/~gitbook/image?url=https%3A%2F%2Fcdn.mathpix.com%2Fcropped%2F2023_06_18_3e182b40eb809e86a4a2g-62.jpg%3Fheight%3D1031%26width%3D1095%26top_left_y%3D272%26top_left_x%3D1251&width=768&dpr=4&quality=100&sign=1054f43d&sv=1)
{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.
![](https://peterlulu666.gitbook.io/~gitbook/image?url=https%3A%2F%2Fcdn.mathpix.com%2Fcropped%2F2023_06_18_3e182b40eb809e86a4a2g-63.jpg%3Fheight%3D1014%26width%3D1057%26top_left_y%3D289%26top_left_x%3D1262&width=768&dpr=4&quality=100&sign=5cbd74a1&sv=1)
{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.
![](https://peterlulu666.gitbook.io/~gitbook/image?url=https%3A%2F%2Fcdn.mathpix.com%2Fcropped%2F2023_06_18_3e182b40eb809e86a4a2g-64.jpg%3Fheight%3D1115%26width%3D1093%26top_left_y%3D187%26top_left_x%3D1252&width=768&dpr=4&quality=100&sign=8b130992&sv=1)
{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?}
![](https://peterlulu666.gitbook.io/~gitbook/image?url=https%3A%2F%2Fcdn.mathpix.com%2Fcropped%2F2023_06_18_3e182b40eb809e86a4a2g-68.jpg%3Fheight%3D756%26width%3D749%26top_left_y%3D438%26top_left_x%3D735&width=768&dpr=4&quality=100&sign=5c844a9d&sv=1)
Last updated