Basic JavaScript: Accessing Object Properties with VariablesPassed

I don’t get how this works. I passed the challenge by watching the video, but I don’t understand this example. Basic JavaScript: Accessing Object Properties with VariablesPassed

var someObj = {
  propName: "John"
};  // So far, so good.

function propPrefix(str) {
  var s = "prop";
  return s + str;
}  // Now I'm lost. So  this returns the string "prop" plus str from propPrefix? Clearly not.

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

I don’t understand how the function works. How does var s relate back to propName? Does (str) mean propPrefix takes a string as an argument? I read this function as it will return “prop” + whatever argument is in the (str). But clearly that’s wrong.

Do I need to go back and review something?

That is correct, why do you think it is wrong?

someProp -> “propName” so it is the same as doing someObj["propName"]

console.log(someProp); // "propName"
console.log(someObj["propName"]); // "John"
console.log(someObj[someProp]); // "John"

Does this post help?

Thank you for the replies. I have fortified myself with more coffee, looked at the example Jeremy provided, but I’m still confused.

To me, it looks like the function propPrefix is completely unrelated to someObj. But doesn’t propPrefix have to know to go to someObj to get the name John?

I wouldn’t worry too much about the specifics of this exact example. Sometimes toy examples can be confusing.

What this is trying to show is that there may be reasons why the name of the property you wish to access could be stored in a variable. When the property name is stored in a variable, then you must use bracket notation instead of dot notation.

OK, thanks. I’ll move on and assume it will become clear to me with more practice.