Accessing object

var someObj = {

  propName: "John",

};

function propPrefix(str) {

  var s = "prop";

  console.log(s + str);   //output "propName"

}

i got confuse about the the output of the console. can anyone pls explain

I’ve edited your post for readability. When you enter a code block into a forum post, please precede it with a separate line of three backticks and follow it with a separate line of three backticks to make it easier to read.

You can also use the “preformatted text” tool in the editor (</>) to add backticks around text.

See this post to find the backtick on your keyboard.
Note: Backticks (`) are not single quotes (’).

Can you give more detail about what is happening that confuses you?

below is the details from freecodecamp

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

to know the value of the “return s+ str” i had to console log it and i was amazed at the out but don’t understand its so. Hence i needed some to help me out

Ok.
At this point, I’m assuming that you’re comfortable with getting properties from objects.

Are you comfortable with how all of these work?

var someObj = {
  propName: "John"
};
console.log(someObj.propName);
var someObj = {
  propName: "John"
};
console.log(someObj['propName']);

and

var someObj = {
  propName: "John"
};

var nameKey = 'propName';
console.log(someObj[nameKey]);

I absolutely understand it, i know how it works

Cool. So the only part added here is the propPrefix() function.
propPrefix() takes a string and returns a modified string. In this case, it is built on the assumption that all of the property names in someObj all follow the same pattern: they start with “prop”. Based on that assumption, if I wan the name value, I would need “propName”. If I wanted the address it would probably be “propAddress”.
The propPrefix()function takes in a string as a parameter, which should be the unique part of the property name. The function then just returns a string with “prop” added to the front.

That means that we can do

var someObj = {
  propName: "John"
};
var someProp = propPrefix("Name");
console.log(someObj[someProp]);

or even

var someObj = {
  propName: "John"
};
console.log(someObj[propPrefix("Name")]);

and have it work exactly the same.

Let me know if I completely missed the part that you meant to ask about. :smiley:

Your explanation is clear and precise. Thank you so much. let me get back on the course…

1 Like

I’m glad I could help. Happy coding!