JavaScript Objects
These are considered a data structure in JS. Objects are just a collection of properties. (Perhaps it's appropriate to compare them to the objects created in structs/classes in C++). There are some specific restrictions in JS, but all properties consist of a key-value pair. You may remember this distinction when thinking back to learning about JSON (JavaScript-Only Notation)
An object allows us to access data using custom keys, rather than an index. Let's look at an example:
const martyDreamboat = {
height: 160,
weight: 160,
name: 'McFly',
leastFavouriteColor: 'Yellow',
hobby: 'Hoverboarding'
}
Notice how the above object has a bunch of keys, each with an associated value! We have five
pairs of key-value information inside this object, labelled martyDreamboat.
Another example:
const user1230{
username: 'crazyCatLady',
upvotes:7,
text:'Gnarrr!!!'
}
property = key+value
Object Literals
An object literal refers to a means of storing a key-value pair. Let's look at how to construct a person:
const person = {firstName:'Mick',lastName:'Dundee'};
When we create an object, we can use almost anything as a value, as long as we remember that it'll be one of the 7 basic possible types used in JS. Something like Reddit will have the following types of values associated with the average comment:
let comment ={userName:'paulB',downVotes:19,upVotes:259,netScore:240,commentText:"That's what she said",isGilded:false};
If you really need to, you can sketch out the object, putting each variable on a separate line. However,
my own familiarity with objects in C++ has helped me bypass this need!
Also of note, we only use the curly braces, {...} when we're creating the object itself. When we want to access the data out of objects, we need to use the name of the KEY, enclosed in [...] square brackets, AND a pair of double quotes! For example,
comment["upVotes"]; //This will return 259!
In more basic form, object["key"]; will give us access to the value of the key to the
property being held within a specific object. I imagine that with access comes the relatively easy
ability to change the value associated with that key! If we spell the key incorrectly,
then we'll get an answer of undefined. Another, and slightly easier option, is to
access the value of a key-value pair using the dot
operator!
Remember: all keys get converted into strings.
const years = {1999:'GOOD',2020:'BAD'};
Behind the scenes in JavaScript, all keys are converted to strings. So, our seeming
integer value of 1999 will be converted to string. When we search for years[1999], we
will get the value 'Good' returned. However, when we look for years["1999"], we'll get the same result.
The TLDR: all key values are converted into strings!
The Coding Exercise 30 was the first one in this course to make me think long and hard about the answer! Essentially, we're given the following object:
const restaurant = {
name:'Ichiran Ramen';
address: `${Math.floor(Math.random()*100)+1} Johnson Ave`;
//Note the use of backticks with the template literal!
city: 'Brooklyn';
state: 'NY';
zipcode: '11206';
}
We are asked to create the variable fullAddress, which incorporates the
address/city/state/zipcode from the restaurant object. Note that we're not trying to insert a new
key-value pair (where the key is 'fullAddress') into the restaurant object! The best answer involves the
MODERN use of template literals!
let fullAddress=`${restaurant.address}+${restaurant.city}+${restaurant.state}+${restaurant.zipcode}`;
The above gives
'7 Johnson Ave+Brooklyn+NY+11206' in our console, when we ask for the variable
fullAddress.
Modifying Objects
Let's use the following example:
const midterms = {danielle:96, thomas:78};
Let's say we want to change thomas's score to 79, we'll use:
midterms.thomas = 79;
That's fairly easy, isn't it? Use of the dot operator makes updating the properties
very simple!
If we really want to, we can change the grade into a string grade, such as:
midterms.thomas = 'C+';
Fairly strict grading, but Thomas now finds his grade updated to a string!
It's also very easy to add new key-value pairs into the object:
midterms['antonio'] = 'A-';
midterms.ezra = 'F';
As you can see, the syntax of JavaScript allows for a great deal MORE flexibility than that of C++!
Midterms will read: {danielle:96, thomas:'C+',antonio:'A-',ezra:'F'};
Arrays & Objects
A very common pattern in C++ is to use an array with a bunch of objects inside, or vice-versa!
for-loops
There are multiple types of for-loops in JS:
- for-loops
- while-loops
- for...of loops
- for...in loops
for-loops
The syntax is identical to that used in C++:
for(let i = 1; i <= 10; i++)
console.log(i);
Just notice that we don't need to define the type of the variable. It's quite common
just to use the variable name i in practice, but don't forget that variables need to
have meaningful names (Colt, in the course, changes the name i to num!
Regardless of the name, the
above for-loop will print out 1-10.
Be wary of making infinite loops. Check the increment carefully, looking at whether/when they will meet up with the condition!
One really common use of the for-loop is to iterate over an array. For example:
const animals = ['Aardvark','Alligator',...,'Zorialla'];
for(let i = 0; i < animals.length(); i++)
console.log(animals[i]);
This will print out all animals in the array, from Aardvark to Zorilla :)
for(let i = animals.length()-1; i>=0; i--)
console.log(animals[i]);
This prints out all animals, from Zorilla to Aardvark!
//Probably notable only as a means to avoid needing to use the 'reverse' function :)
Recently, another method has come into vogue...
while-loops
We take the opportunity to use these in this section...
for-of loops
These make it much easier to iterate over arrays - or anything else that is iterable, such as strings, maps and sets. The basic form is:
for(variable of iterable){
statement;
}
let beatles = ['John','Paul','George','Ringo'];
for(let member of beatles){
console.log(`${member}`);
}
This seems to be equivalent to for (string member:beatles){...} in C++. The for-of
looks like a variation on the use of :
Iterating over objects
One way to iterate over an object is to use the for...in loop. It's rather uncommon these days, but is still useful!
const testScores = {
keenan:80;
kel:5;
roger:99;
orange:0;
soda:10;
}
for(let person in testScores){
console.log(`${person} scored $testScores[person]`);
} }
The above code, uses template literals very nicely to print out the person's name and
their score:
console.log(`${person} scored $testScores[person]`)
We could use something like Object.keys(testScores); to access our set of keys, Object.values(testScores); for the values, and Object.entries(testScores); to get a list of key-value pairs inside the object! As an example:
const testScores = {
keenan:80;
kel:5;
roger:99;
orange:0;
soda:10;
}
let total = 0;
let scores = Object.values(testScores);
for(let score of scores){
total+=score;
}
console.log(total/scores.length);
To Do List Project
The last thing we'll handle in Section 19 of the course is a project. The whole thing will be shown here