Accessing Object Properties with Variables_ question from example from course reading

Hello All,
I have a question about the Accessing Object Properties with Variables exercise or rather more from the example given within the course material in regards to bracket notation.
Within the course material is given this example below:

 var someObj = {
  propName: "John"
};
function propPrefix(str) {
  var s = "prop";
  return s + str;
}
var someProp = propPrefix("Name");
console.log(someObj[someProp]);

I’m having trouble understanding what is the purpose of the propPrefix function? Why do we need this function in order to print out just the name John? I’ve tried console.log(someObj); which outputs to the console { propName: ‘John’ } which I see it is literally printing out the someObj object but I’m having issues understanding how the propPrefix function when added as the value for the variable someProp is needed and what exactly is happening when someProp is being added to the console.log so in other words why do we need someProp to be added like this: console.log(someObj[someProp]) to just print out the name john? I apologize if my wording is bad , I find asking questions challenging and I know this is an area I need to get better in. also I’m aware this is an example given to understand bracket notation I just cant seem to follow the logic.

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

Challenge: Accessing Object Properties with Variables

Link to the challenge:

Hi @manbodhclaude !

The only thing that the propPrefix function returns is "prop" + str
With this function call propPrefix("Name") it will return propName
propName is then assigned to someProp.
That is what this line of code does

When you console.log someObj[someProp]
the variable of someProp has ‘propName’ assigned to it.

Another way to look at it would be this
someObj['propName'] which results in “John”

Hope that makes sense!

1 Like

Hi Jwilkins and thank you for the help! I finally see it now ohhhhhhh lol its crazy how getting insight or feedback from someone helps you see the question or challenge differently, thanks so much!! I haven’t had time to look at this since this morning and after reading your explanation I finally saw that yes the function propPreFix is making the variable someProp === to propName which in turn is the property name in the someObj object which is how the name “John” gets printed out. geeze i made this one harder then it had to be, im new to this part of coding or I guess assigning variables to functions and basically accessing object properties and variables. Thanks again!

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.