Accessing Object Properties with Variables - can someone please explain this lesson to me?

Accessing Object Properties with Variables - can someone please explain this lesson to me?
0.0 0

#1

Tell us what’s happening:

  1. I am not looking for help with figuring out the answer to the challenge but someone to explain the explanation.

  2. how in the 1st example is ----- var myDog = “Hunter”; and not var myDog = dogs[“hunter”]?

  3. the 2nd example makes no sense to me at all.

Your code so far


// Setup
var testObj = {
  12: "Namath",
  16: "Montana",
  19: "Unitas"
};

// Only change code below this line;

var playerNumber;       // Change this Line
var player = testObj;   // Change this Line

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.181 Safari/537.36.

Link to the challenge:
https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/basic-javascript/accessing-object-properties-with-variables


#2

The example is showing you how to access a property value using a variable, instead of a string.

You suggest this, which is correct var myDog = dogs["hunter"], but then you hardcode the string into the myDog variable. And in programming we strive to not hardcode any strings, since they don’t scale and lead to repetitive code.

There are many ways to get the same result in computer science. We strive to write code that is predictable and that means each time we repeat the same code, we run the risk of a mistake

Imagine this scenario

var dogs = {
Fido: "Mutt", Hunter: "Doberman", Snoopie: "Beagle"
};

// myBreed here can only ever be "Doberman"
var myBreed = dogs["Hunter"];

console.log(myBreed); // "Doberman"

// if I want Mutt, then I have to assign another variable
var myBreed2 = dogs["Fido"]

console.log(myBreed2) // Mutt

// but if we made it a function value getter, then we can do
var myBreed = breed => dogs[breed]

console.log(myBreed("Hunter")) // Doberman
console.log(myBreed("Fido")) // Mutt

I seems silly to do this for such a simple object as dogs. But in real world apps it makes a huge difference during refactoring and bug tracking.

This is what I explained earlier. Except it’s concatenating the string to access the prop

var someObj = {
  propName: "John"
};

function propPrefix(str) { // <-- function to set correct prop key
  var s = "prop";
  // string concatenation === "prop" + "Name" === "propName"
  return s + str; 
}

var someProp = propPrefix("Name"); // someProp now holds the value 'propName'
console.log(someObj[someProp]); // <--- same as someObj["propName"] === John"

#3

In the first example how does the machine understand ---- var myDog=“Hunter” means you are referring to the object dogs and the property of “Hunter” within it?
How come it does not simply store the string “Hunter” in the var myDog?

I finally understood the second example. The whole point of the function was to generate the key propName. What is the significance of this though? Why didn’t they explain the purpose as you explained by writing the following? I’m asking cause I felt this was made way more complicated than it should have been. Please correct me if you don’t think so


#4

It doesn’t. What you say next is what it’s actually doing

Learning to code is the process of building a mental model of what you expect the code to be doing. My mental model just works for you, which is why you understood it better than theirs. Whereas I had no trouble understanding theirs.

This is programming, and what leads to holy wars over languages, tools, stacks, etc. lol


#5

Oh ok. I get it now. Both of these examples are just generating the key.

“This can be very useful for iterating through an object’s properties or when accessing a lookup table.”
Could you please explain this with an example?


#6

Sure. First let’s clear up some terms for clarification.

  • Iteration
    • this just means the process of looping over items.
    • when you see this, you can just think of for loops, maps, reduce, etc.

A lookup table just means getting a value from some object. That’s getBreed below.
If you want to loop over an objects properties, and have a list of props, you can do this: getAllBreeds

const breeds = ["Fido", "Hunter", "Snoopie"]
const dogs = {
  Fido: "Mutt", 
  Hunter: "Doberman", 
  Snoopie: "Beagle"
}

// using arrow functions & es6
const getBreed = breed => dogs[breeds]
const getAllBreeds = breeds => breeds.map(breed => dogs[breed])

// standard version
function getBreed (breed) {
  return dogs[breed]
}

function getAllBreeds(breeds) {
  const allBreeds = []

  for (let i = 0; i > breeds.length; i += 1) {
    allBreeds.push(dogs[i])
  }

  return allBreeds
}

// Now we can get all breeds, one breed, 
// or any other getter function we write.
console.log(getBreed('Fido') // Mutt
console.log(getAllBreeds(breeds) // ['Mutt', 'Doberman', 'Beagle']

If you don’t have a list of names in advance, then you can get them from the object at runtime

const dogs = {
  Fido: "Mutt", 
  Hunter: "Doberman", 
  Snoopie: "Beagle"
}

const breeds = Object.keys(dogs )// ["Fido", "Hunter", "Snoopie"]

...

Hopefully that clears it up a bit.


#7

Thanks man, you’ve been very helpful