Accessing Object Properties with Variables - problem with property name

Hello everyone,

I’m new on the forum. I have achieved the responsive web design certification and I’m on my way through the second certification on JavaScript algorithms and data structures certification. I am currently stuck on the " Accessing Object Properties with Variables" lesson.

There is this code I don’t quite understand, and this is it:

1     var someObj = {
2     propName: "John"
3     };
4     function propPrefix(str) {
5     var s = "prop";
6     return s + str;
7     }
8     var someProp = propPrefix("Name");   // someProp now holds the value 'propName'
9     console.log(someObj[someProp]);       // "John"

Lines 1-3 are clear to me, but I have some questions on the rest of the code:

  1. What’s the reason to declare the variable s on line 5 and assign it “prop” ? Couldn’t one just simply write return “prop” + str; on line 6 to make the same effect?

  2. This is the real doubt: why on line 8 does propPrefix(“Name”); now holds the value ‘propName’? I mean, the names don’t match.

Thanks in advance to anyone who will be willing to help me out.

1 Like
  1. Yes, you don’t need the variable to do the string concatenation.

  2. The propPrefix function returns the string “propName” and the variable someProp is use to capture the return string which is then used to access the object property. So doing someObj[someProp] is the same as someObj['propName']


Welcome to the forum…

  1. It can be done in multiple ways,one is the way you mentioned,but take in consideration that sometimes you would like to hold some data inside certain variable and use it through function,but it works in the same way.

2.on line 8,the variable someProp will hold string propName because that is what is returned from the propPrefix(). propPrefix function explicitly returns s + str


I see now. So, declaring the variable s can be useful in some scenarios, understood.

I still have to wrap my head around the second point, my second question.

Thanks for answering!

1 Like