Access object properties with variables

I’ve came across this in one of the challenge:


Another way you can use this concept is when the property’s name is collected dynamically during the program execution, as follows:

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

someProp would have a value of the string propName , and the string John would be displayed in the console.


I don’t understand how the entire code work. Can someone explain it?

Hi @TLJ97 !

We know that we can access the property of an object using bracket notation right?

For example, this would be the basic syntax


For this object here

If I wanted to access this property I would write someObj['propName']

What this function does, is that it concatenates “prop” with str

When you call the function here

What gets returned is "propName" and that is assigned to the variable someProp.

When you console.log(someObj[someProp])
What you are really saying is this


Hope all of that makes sense!

Alright I understand how it works now. Thanks a lot Jessica! But do you mind telling me how is this concept useful? If I were to access the value of a property I could just console.log(someObj[propName]) instead of doing all the concatenation or accessing var or calling functions etc.

I guess it could be useful if you are testing it with multiple strings.
Or if you don’t know the string ahead of time and you are getting that data from somewhere like user input.


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