Lost in Accessing Object Properties with Variables

Hi All,

I’m on lesson 81 of the Basic JavaScript course and I have come to a point where the example code has me lost. I’m taking special care to really grasp the concepts before moving forward, so maybe someone can help me understand what is happening in this bit of code. I’m particularly lost by the propPrefix function, how it works or what purpose it serves.

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"

It is a little convoluted, for sure. That function just builds and returns a string. It returns the string “propName”. Put in some console.log statement to see what happens a various points. This is a useful skill for a dev.

Why do they do it that way? Just to combine different skills. It’s overkill in this situation, but it’s not completely crazy. I’ve had to dynamically generate property names and sometimes I’ve used a little helper function to do it.

1 Like