Can someone break down and explain this to me?

Tell us what’s happening:

  **Your code so far**

var someObj = { propName: "John" }; 

function propPrefix(str) { 
var s = "prop"; 
return s + str; 
} 

var someProp = propPrefix("Name"); 
console.log(someObj[someProp]);

  **Your browser information:**

User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.90 Safari/537.36.

Challenge: Accessing Object Properties with Variables

Link to the challenge:

Which part are you struggling with?

Maybe try console.logging what this is:

var someProp = propPrefix("Name");

Then think about what this is (remember object bracket notation):

someObj[someProp]
1 Like

Yeah, it would be very helpful if you would make it clear exactly what the problem is, so we don’t have to go line by line, character by character.

So we have an object called someObj and inside we have the property called propName with value "John". If we use console.log(someObj.propName) or console.log(someObj["propName"] it will log to the console its value- "John". Those are two ways of accessing values of object properties, by dot or bracket notations.
We also have a function, which accepts an argument and returns a string which is equal the value of its local variable s and its argument. If we use console.log(propPrefix("Name")), we will log to the console the string "propName". As you can see we assign to the variable someProp this same string("propName").
In the end we log to the console the value of the property named with the value of someProp, which is found within the someObj, which log "John"

1 Like

It would be helpful if you were helpful.

OK then, good luck to ya.

Thanks for your constructive input…

Did @Sylvant answer help you?


The code is a little convoluted, if you ignore the function and just look at the string concatenating and property access it might be clearer.

const someObj = { propName: "John" };

const str1 = 'prop'
const str2 = 'Name'

const propertyVariable = str1 + str2;

console.log(someObj[propertyVariable]); // John

// Same as 
console.log(someObj['propName']); // John

Although if it’s the function part that is confusing you I guess maybe this didn’t really help.

1 Like

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