Trouble in understanding the concept - Accessing object properties through variables


I was looking into the concept of accessing object properties, through dot notation, bracket notation and even by the variables. Then, I came across to a code on FCC that is spinning my head around. Here is the code…

var someObj = {
  propName: "John"
function propPrefix(str) {
  var s = "prop";
  return s + str;
var someProp = propPrefix("Name");

The above code is breaking the property “propName” into two parts - the “prop” from "propName is assigned into “s” variable then it is concatenated with the other half “Name”, again from “propName”.

I am not able to understand, why it is broken into two parts and how the heck code works???

Thank you very much!

var someProp = propPrefix(“Name”)
This is calling a function (propPrefix) and passing in a string (“Name”). “someProp” will be initialised as the result of this function (once we know what it will return.

The propPrefix function has one input (str), which in this example is equal to “Name”. The propPrefix function then declares a variable (s) and initialises it to the string “prop”. The propPrefix function then returns the addition of the two stored variables (s + str) which is “prop” + “Name”, which gives us “propName”

So the someProp = “propName” (remember it is setting someProp to be equal to the return value (“propName”) of propPrefix(“Name”).

The final line is a console.log of an object (someObj), which is defined on line 1. someObj is an object with only one key-value pair (propName: “John”).

So console.log the value of the someObj key-value pair with the key of someProp (which equals “propName”). Basically it is saying; go to the someObj object and look for a key called “propName” and tell me what value is associated with it. This is why console.log(someObj[someProp]); writes “John” to the console.

Hope that makes sense. Happy Coding :slight_smile:

P.S. “why it is broken into two parts?” Just to show you that you can do it. Sometimes you will want to be able to access props (keys of the object) dynamically.