Day 3: Arrays and Objects

Wednesday, May 16, 2018

Lecture Videos

Morning:

Afternoon:

Topics

Arrays

Objects

  • Object literals
  • Property Naming
  • Retrieving property values
  • Setting property values

Arrays and Objects CodePen Example

Handling exceptions

  • try
  • catch
  • finally

Styling

Flexbox

Fonts

Tips and Tricks on CSS

Examples

Arrays

Arrays are extremely useful data structures in JavaScript, as they can be easily iterated and transformed through methods like map, filter, and reduce. Sometimes, you may have an ‘array-like’ collection (like a NodeList or function arguments) that you would need to convert to an actual Array before you could use these methods. This can be done using Array.from



let paragraphs = document.querySelectorAll('p')
paragraphs.map((p) => {
  p.textContent = "This won't work because paragraphs is a NodeList, not Array!"
})
// => Uncaught TypeError: paragraphs.map is not a function

let actualArrayOfParagraphs = Array.from(paragraphs)
actualArrayOfParagraphs.map((p) => {
  p.textContent = "This totally does work because we created an Array from our NodeList!"
})


Requirements for 'Array.from'

What objects can you convert to an Array using ‘Array.from’?

  • Any array-like object with a ‘length’ property and indexed elements
  • Iterable objects (like Map or Set)

For more info, check out this article on MDN.

Objects

Almost everything in JavaScript is an Object. The easiest way to create new Objects is with the object initializer, more commonly known as ‘object literal’ syntax. Basically, use curly braces to make an object {} and fill in the properties that you want.

Objects contain key/value pairs that allow you to set and retrieve values from them.



// create a new object and assign some properties
const myObject = {
  prop1: 'Hello there',
  prop2: 42
}

// access the values in several ways, usually 'dot' or 'square bracket' notation
myObject.prop1 // => 'Hello there'
myObject['prop1'] //=> 'Hello there'

// new key/value pairs can also be assigned with these notations
myObject.prop3 = 'New Value!'
myObject['prop4'] = 'Newest Value!'

console.log(myObject)
// { 
//   prop1: 'Hello there',
//   prop2: 42,
//   prop3: 'New Value!',
//   prop4: 'Newest Value!'
// }


We know that we can iterate through an Array using map or forEach. Can we do something similar with objects? There are a few ways to do it, but one of the newest and easiest is the Object.keys method. It iterates through the enumerable properties of an object, returning an array of the property keys. Once we have an array of keys, we can map over that and access each of the object properties individually.



const myObj = {
  a: 'hi',
  b: 42,
  c: [1, 2, 3]
}

const myObjKeys = Object.keys(myObj)    // ['a', 'b', 'c']

myObjKeys.map(key => myObj[key])        // ['hi', 42, [1, 2, 3]]


Handling exceptions

In JavaScript (as in many languages), there is a way to ‘try’ a block of code that may produce an exception, and if it does produce an exception, ‘catch’ it and execute a different block of code. The catch block receives the exception as an argument. There is also an optional ‘finally’ block, which will always run, regardless of whether there was an exception.



try {
  // try running this code first
  somethingThatMightBlowUp()
} catch (e) {
  // executes if the 'try' block produced an exception
  logMyErrors(e)
} finally {
  // always executes after the previous blocks have run
  console.log("Done!  Maybe there was an exception, maybe there wasn't.")
}


For more info, read this MDN article.

Projects

User Directory

Final Version

Homework

Create a brand-new app to create a list of something. For example: Tatum Tots, our favorite Channing Tatum movies.

You should be able to type an item into a form and have it added to a list (a ul).

Bonus Credit

In addition to building a list item and adding it to the DOM, also store each item in an array.

Super Mega Bonus Credit

Add a delete button to each list item that removes it from the list.

Super Mega Bonus Credit Hyper Fighting

Remove the item from the array as well.