Accessing Object Properties with Variables example explaination

Accessing Object Properties with Variables example explaination
0

#1

I was wondering if somebody could explain to me what the mid section of the example code does. I can’t see how the var s section has anything to do with the actual coding but if it is removed, the code doesn’t run on Repl.it. I can pass the test, I’m just very curious.

var someObj = {
  propName: "John"
};
//what does this section do?
function propPrefix(str) {
  var s = "prop";
  return s + str;
}
var someProp = propPrefix("Name");
//someProp now holds value "propName"
console.log(someObj[someProp]);
//john

#2

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 easier to read.

See this post to find the backtick on your keyboard. The “preformatted text” tool in the editor (</>) will also add backticks around text.

Note: Backticks are not single quotes.

The function below returns the string “propName”.

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

You will notice the result of this function is assigned to the variable someProp, so that you can access the property named “propName” in the someObj object.

The last line is the equivalent of:

console.log(someObj["propName]); // displays John

#3

I’m sorry, I just still don’t understand what the var s does


#4

Why is it that if the “prop” in var s = “prop” is changed to anything else, it won’t work?
It is the only instance of the “prop” string and is not a keyword. Can you please explain further or point me to some resources? I am very confused haha. Thanks :smile:


#5

The variable s is assigned the value “prop” which is just a string. If you assigned s a different value like “coffee”, then the return statement of s + str, would return “coffeeName” if propPrefix was called as follows:

var someProp = propPrefix("Name");

Assuming var s = “coffee” inside the function, the above code would assign the value undefined to someProp, because there is no property named “coffeeName” in the object named someObj.


#6

Why would anyone want to access the property of an object like that? I’m sure there must be a real life scenario where this would be useful, but I don’t see it.