CS133JS Beginning Programming: JavaScript
| Topics by Week | |
|---|---|
| 1. Intro to JavaScript programming | 6. Arrays |
| 2. Functions, Operators and Expressions | 7. Objects and Object Constructors |
| 3. Conditional Statements: if and switch | 8. Web Site I/O |
| 4. Repetition: while, do while, and for | 9. Review |
| 5. Midterm Check-Point | 10. Final |
IntroductionQ and AReview of Array MethodslengthindexOf()spliceconcatpopshiftpushunshiftOverview of objectsCreating ObjectsProperties and MethodsPropertiesMethodsAccessing Properties and MethodsEncapsulationAccessing an Object PropertyThe this keywordCalling a Method on an ObjectAdding and Removing Properties and MethodsAdding Properties to an ObjectAdding Methods to an ObjectRemoving Properties from an ObjectUsing Loops with Object Propertiesfor...in Loop—Just for ObjectsAll the Other LoopsGet an Array with Object.keys() or Object.values()for Loopwhile and do...while LoopsMutability of ObjectsReferences
Registration is open for next term!
Upcoming classes for the Software Development AAS degree program
Lab 5 on Arrays— any questions?
Code review due Tuesday.
Production version due Thursday.
Reading quiz due Thursday.
Does anyone have any other questions about anything?
These examples use the array declared and initialized below:
let continents = ["Asia", "Africa", "North America", "South America", "Antarctica", "Europe", "Australia"];
lengthxxxxxxxxxxconsole.log(continents.length);indexOf()xxxxxxxxxxconsole.log(continents.indexOf("Antarctica"));splicexxxxxxxxxxcontinents.splice(3, 0, "Atlantis"); // Insert Atlantis at index 3continents.splice(3, 1); // remove Atlantiscontinents.splice(2, 2, "Americas"); // Remove N. and S. America, replace with Americasconcatxxxxxxxxxxlet tooks = ["Merry", "Pippin"];let bagginses = ["Bilbo", "Frodo"];let hobbits = tooks.concat(bagginses);Copy an array.
xxxxxxxxxxlet hobbitsCopy = [].concat(hobbits);popxxxxxxxxxxlet continent = continents.pop(); // removes Austrailiashiftxxxxxxxxxxlet continent = continents.shift(); // removes the first element, Asiapushxxxxxxxxxxlet arrayLength = continents.push("Austrailia"); // adds Austrailia at index = lengthunshiftxxxxxxxxxxlet arrayLength = continents.unshift("Asia"); // adds Asia at index 0
Objects in JS are like objects in the real world. They have properties--for example a book has: title, author, publication date, genre, etc. They can also have methods--for example a book could have a countWords method that counts all the words in the book.
Objects can contain:
Properties
Methods
There are two ways to create an object:
Object constructor
xxxxxxxxxxconst fili = new Object();We'll cover object constructors in the next class.
Object literal
We'll focus on this approach today.
This code will create an object literal without adding any properties or methods:
xxxxxxxxxxconst thorin = {};This is how you create an object with properties and methods:
xxxxxxxxxxconst fili = { name: "Fili", race: "dwarf", brother: "Kili", greet: function() { return this.name + " at your service!"; }};
Think of a properties as nouns, and methods as verbs.
Each property consists of a key : value pair. In the example above, name is a key and "Fili" is a value.
A method is essentially a function. It is also the value of an object property. It is a task that an object can perform. In the example above, greet is a key, and is the name of the method. The function is a value.
The scope of properties and methods declared inside an object is limited to that object. The rule about local scope being delineated by the curly braces applies here. There is a special word for the scope of properties and methods inside an object. We say they are encapsulated in the object.
Here are two ways to access an object’s properties.
Dot notation: .
xxxxxxxxxxfili.race;Bracket notation: []
xxxxxxxxxxfili["race"];Bracket notation must be used if an object’s property name is a number.
xxxxxxxxxx// Create a new object containing numeric propertiesconst elves = { home:"Rivendell", 0:"Elrond", 1:"Arwen", 2:"Gildor"};// Access a numeric propertyconsole.log(elves[1]);What do objects with numeric properties look like?
this keywordInside a method, the this keyword references the object that contains the method so you can access an object property.
xxxxxxxxxxconst fili = { name: "Fili", greet: function() { return this.name + " at your service!"; },};
You call a method just as you would call a regular function, but you do it through the object.
xxxxxxxxxxfili.greet();Add new properties to an object with the assignment operator, =
xxxxxxxxxxfili.age = 82;fili.weapon = "hammer";Adding a method to an object is similar to adding a property, but in place of the property value you provide a function definition.
xxxxxxxxxxfili.fight = function() { return "Fili attacks with a " + this.weapon;}utilize the delete keyword. Evaluates to true if successfull.
xxxxxxxxxxdelete fili.weapon;delete elves[1];for...in Loop—Just for ObjectsThe JavaScript language has a special, predefined loop, for...in, that is specifically designed for iterating over the properties of an object. This loop only iterates over property keys (aka names). Note that you need to use bracket notation.
xxxxxxxxxxfor (let item in fili) { console.log(fili[item]);}Object.keys() or Object.values()JavaScript objects have a pre-defined method for getting an array of property keys, the Object.keys() method. This makes it easy to use all the other loops with object properties.
xxxxxxxxxxlet filiKeyArray = Object.keys(fili);You can also get an array of all the values in an object like this:
xxxxxxxxxxlet filiValueArray = Object.values(fili);
####for...of Loop—Just for Arrays
The for...of loop is specifically designed to operate on arrays.
xxxxxxxxxxlet filiArray = Object.keys(fili);for (const key of filiArray){ console.log(key, fili[key]);}for LoopThe for loop has a built-in loop counter that works great for indexing an array.
xxxxxxxxxxlet filiArray = Object.keys(fili);for (let i = 0; i < filiArray.length; i++){ let key = filiArray[i]; console.log(key, fili[key]);}while and do...while LoopsWe can use these loops on arrays of object properties too, but they aren't as convenient to use as the three types of for loops.
xxxxxxxxxxlet filiArray = Object.keys(fili);let i = 0;while (i < filiArray.length){ let key = filiArray[i]; console.log(key, fili[key]); i++;}Objects declared with const are mutable, that means they can have their properties changed or removed and can have new properties added. But the binding is immutable, the object variable can't be assigned to a new object.
xxxxxxxxxxconst bomber = {name:"Bomber"};const boffer = {name:"Boffer"};bomber = boffer; // this will cause an errorlet balin = {name:"Balin"};balin = boffer; // this works!
JavaScript Object Basics - MDN Guide
Understanding Objects in JavaScript - Tania Rascia, 2021, Digital Ocean
"Data Structures: Objects and Arrays", Ch. 4 in Eloquent JavaScript, 4th Ed., Marijn Haverbeke, 2024, No Starch Press.
Beginning JavaScript Lecture Notes by Brian Bird written in 2020 and revised in are licensed under a Creative Commons Attribution-ShareAlike 4.0 International License.