Basic JavaScript: Accessing Object Properties with Variables

Basic JavaScript: Accessing Object Properties with Variables

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"

I’m trying to understand this so I tried writing my own

Here’s what I wrote,

//create an object
var myObj = {
  propName: "Dog"

//create a function to access the property "Noe from the myObj object"
function propPrefix(str) { // propPrefix is just a function name, str is an argument variable
  var y = "prop"; // y is a variable that stores "prop"; is this how "noe" is being accessed? //"prop" has to be referring to "Noe" in myObj
  return y + str; // y = prop, "prop = ? possibly accessing from propName" ;;; str = function argument var

var someProp = propPrefix("Name"); // this runs the propPrefix function where "Name" + y which is "prop" --- WHUT? // what is "Name"? Just some arbitrary word?

console.log(myObj[someProp]); // where is someProp coming from? ohhh someProp = the propPrefix function, name is the argument, 

My biggest question is why is “Name” special in the propPrefix function all? Isn’t Name just a variable that’s being passed through? y + str should be my “prop” from the object but the function returns “prop” + “name” and that logs “Noe” but if I change “Name” in the function call, it doesn’t work.

I don’t understand why this works. Hoping for some clarification. Thanks.


So the property name is stored as object.propName – but you’re looking for a Name property. What this is doing is making a method to append the prefix prop to any property name. Assuming you also create setters for those same properties, you could do myObj.set(propPrefix("Name"), "Dog").

Internally, you’re using a slightly different name than the external user might see – basically, using propPrefix simply changes Name to propName, or Age to propAge, or whatever. Then you can access that property, assuming it exists.

Yeah, what @DanCouper sez. :wink:


propPrefix is a function that takes any string and returns that prefixed with “prop”. So propPrefix("Name") is the same as “propName”, propPrefix("cat") is the same as “propcat” and so on.

myObject has a property “propName”. So myObject["propName"] will access that property, nothing else will


OHHHH! I totally get it now.

Thanks for the explanation guys Have a great day!