DEV Community

benboorstein
benboorstein

Posted on • Updated on

My Raw Notes for the Week of 10-11-2021

ENGLISH:

Slides for course:
https://slides.com/bgando/f2f-final-day-1 (navigate with arrows at bottom-right of top image)
https://slides.com/bgando/f2f-final-day-2 (navigate with arrows at bottom-right of top image)

Core data structures: objects and arrays

"Anything that ever uses a dot in JavaScript is an object."

var person = {}
person.name = 'Mrs. White' // 'Mrs White' is now stored in 'person.name', i.e., 'person.name' now POINTS TO 'Mrs. White'
person.name // 'Mrs. White' // this is a "look up"
var who = person.name // 'who' now stores 'Mrs. White', i.e., 'who' will now return 'Mrs. White'
who // 'Mrs. White'
But, if we do this (i.e., reassign)...
person.name = 'Mr. White'
...what happens?
person.name // 'Mr. White'
who // 'Mrs. White'
Explanation: 'person.name' now points to 'Mr. White', but 'who' still stores 'Mrs. White' (and the place in memory where 'Mrs. White' is being pointed to by 'person.name' will get "garbage collected")

Arrays are a type of object, but arrays are also a bit different because of the methods (e.g., '.push()') and certain properties (e.g., '.length') they have on them. Also remember that arrays are ordered and objects are not.

Dot notation "stringifies". Bracket notation does not.
I.e., dot notation coerces to a string.
How to explicitly "stringify" while using bracket notation? Add quotes.
So: arrayName.xxx === arrayName['xxx'].
However, using 'arrayName.0' to access the zeroth index doesn't work because it's a syntax error (basically the parser gets confused). Use 'arrayName[0]'.

Bracket notation works for all cases and dot notation only works for strings. So why use dot notation at all? Fewer characters to type. That's it.

This was in the console (with content before it that I'm not including):
  person
    [name: 'Mrs. White', plea: 'I would never!']
    name: "Mrs. White"
    plea: "I would never!"
    length: 0
The question: Why is 'length' equal to '0'?
The answer (from Robert):
- the 'length' property only counts the number of *numbered* keys
- 'name' and 'plea' are not numbered keys
- if you set 'person[0] = "I would never!"', 'length' would be '1'
- if you set 'person[4] = "I would never!"', 'length' would be '5', given that JS would add empty indices, and then a key-value pair of '4: "I would never!"'

Separate note:
- If you write an array and log it to the console, the array will appear in the order you wrote it, at least in the Chrome console
- If you write an object and log it to the console, the object will appear in alphabetical order, at least in the Chrome console

Destructuring (from ES6):

  Arrays:
    const [first, second] = [true, false] // what's to left of '=' is called 'The Target' and what's to right of '=' is called 'The Source'
    first // true
    second // false

    const [a, b, c] = [true, false] // FYI, if there are more variables declared than values assigned, below is what happens
    a // true
    b // false
    c // undefined

  Objects:
    const {first, second} = {first: 0, second: 1} // what's to left of '=' is called 'The Target' and what's to right of '=' is called 'The Source'
    // Remember that, because order doesn't matter with objects, the above line would behave the same if it were...
    // ...'const {first, second} = {second: 1, first: 0}' or 'const {second, first} = {first: 0, second: 1}'
    first // 0
    second // 1

  Note:
    With array destructuring, what's declared and assigned connects because of the order (in the above example, 'first' comes first and 'true' comes first)
    With object destructuring, what's declared and assigned connects because the variable name matches the key name (recall order doesn't matter with objects)

List Transformations (important when using Functional Utility Methods, her name for the main methods used in Functional Programming):

  Often in frontend development you're dealing with data coming from APIs and you don't really have any control over what format that data comes in, and it's usually not in the format you need it to be in, so being able to reformat this data is important. The FUMs help you do this.
Enter fullscreen mode Exit fullscreen mode
CODE:

// JS
// Create an object using bracket and dot notation that represents the characters and related data you may find in a game of Clue

const game = {}

game.murderer = '??'

game['weapons'] = ['lasers', 'angry cats', 'dish soap']

game.characters = []
game.characters[0] = 'Miss Scarlet'
game.characters.push('Mr. Green')

console.log(game)

// Note: If we change 'game' to an array (i.e., 'const game = []' instead of 'const game = {}'), everything above works the exact same way

//-------------------------------------------------------------------

// JS
const {weapon, room, name} = {name: 'Rusty', room: 'kitchen', weapon: 'candlestick'}
/* Note that the above line is like doing:
const obj = {name: 'Rusty', room: 'kitchen', weapon: 'candlestick'}
const weapon = obj.weapon
const room = obj.room
const name = obj.name
*/
console.log(room, weapon, name) // kitchen candlestick Rusty

//-------------------------------------------------------------------

// JS
// ARRAY DESTRUCTURING EXAMPLES
  // array destructuring
  const [a, b] = [1, 2]
  console.log(a, b) // 1 2

  // array destructuring - omit a value
  const [a, , b] = [1, 2, 3]
  console.log(a, b) // 1 3

  // array destructuring - combine with spread/rest operator (accumulates the rest of the values)
  const [a, ...b] = [1, 2, 3]
  console.log(a, b) // 1 [2, 3]

  // array destructuring - swap variables easily without temp
  let a = 1, b = 2
  [b, a] = [a, b]
  console.log(a, b) // 2 1

    // Note that without destructuring, the above code block would be done this way (which is two lines longer):
    let a = 1, b = 2
    let temp = a
    a = b
    b = temp
    console.log(a, b) // 2 1

  // array destructuring - advance deep arrays (nested)
  // she says this example is "very confusing" and she would recommend not doing this sort of thing; using an object in this case is better because it's clearer
  // the lesson, she says: Don't use super-nested arrays and don't try to destructure "crazy nested arrays like this" 
  // again, she says, make your code readable and straightforward
  const [a, [b, [c, d]]] = [1, [2, [[[3, 4], 5], 6]]]
  console.log('a:', a, 'b:', b, 'c:', c, 'd:', d) // a: 1 b: 2 c: [[3, 4], 5] d: 6

// OBJECT DESTRUCTURING EXAMPLES
  // object destructuring 
  const {user: x} = {user: 5}
  console.log(x) // 5

  // object destructuring - fail-safe
  const {user: x} = {user2: 5}
  console.log(x) // undefined

//-------------------------------------------------------------------

// JS
// looping exercise 1
// loop through the 'game' object's 'suspects' array
const game = {
  suspects: [
    {
      name: 'Rusty',
      color: 'orange'
    },
    {
      name: 'Miss Scarlet',
      color: 'red'
    }
  ]
}

const suspectsArr = game.suspects

function func() {
  for (let i = 0; i < suspectsArr.length; i++) {
    console.log(suspectsArr[i]) // '{name: 'Rusty', color: 'orange'}' and '{name: 'Miss Scarlet', color: 'red'}'
    // console.log(typeof i) // 'number' and 'number'
  }
}

func()

// Note that the above 'for' loop "is just doing math"; it's good for arrays because arrays have numbered, ordered indices. For objects, which are not numbered or ordered, you can use a 'for...in' loop (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...in) 

//-------------------------------------------------------------------

// JS
// looping exercise 2
// loop through all the properties of the 'suspects' array's objects
const game = {
  suspects: [
    {
      name: 'Rusty',
      color: 'orange'
    },
    {
      name: 'Miss Scarlet',
      color: 'red'
    }
  ]
}

const suspectsArr = game.suspects

function func() {
  for (let i = 0; i < suspectsArr.length; i++) { // she says this loop runs 2 times
    // console.log('outer loop') // use this to help you see what order all this code runs in
    for (let prop in suspectsArr[i]) { // she says this loop runs 4 times
      // console.log('inner loop') // use this to help you see what order all this code runs in
      console.log(prop, suspectsArr[i][prop]) // 'name Rusty' and 'color orange' and 'name Miss Scarlet' and 'color red'
    }
  }
}

func()

//-------------------------------------------------------------------

// JS
// destructure this nested data structure into two variables with the string 'red' in one and the string 'orange' in the other
const suspects = [
  {
    name: 'Rusty',
    color: 'orange'
  },
  {
    name: 'Miss Scarlet',
    color: 'red'
  }
]

const [colorRusty, colorMsScarlet] = [suspects[0].color, suspects[1].color]
// another way is: 'const [{color: colorRusty}, {color: colorMsScarlet}] = suspects' 
console.log(colorRusty) // orange
console.log(colorMsScarlet) // red
Enter fullscreen mode Exit fullscreen mode

Discussion (0)