Accessing Object Properties with Variables [Trying to understand an example]

Accessing Object Properties with Variables [Trying to understand an example]
0.0 0


Hello fellow campers,

I would like to know if you could help me understand the following code. Thanks:

var someObj = {
  propName: "John"

//This is  only an  object  with a given property

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

// This  is a function which  there is a  variable  "s"  created which  contains a  string ("prop").
// the  return command  will  yield:  "prop" + what?
//how is this  previous line of  code  (the function) is related to  the initial  variable declaration?

var someProp = propPrefix("Name"); // someProp now holds the value 'propName'

// this is another variable  created which contains the name  of the  function but how come by putting "Name" can  trace  back  to the name  "John"?  Where is the relationship? 

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


Okay. So first, you’ll have to understand how objects are stored in JS. Each object in JS has a key and a value (and also a prototype, but that’s not relevant here). Everything in JS is an object.

value can be anything you want. Usually, it’s another object. Think of that: an object inside an object inside an object inside an object

key is a String. What a string is, is a list of letters. The string 'foo' is a list of f, o, and o. (Nobody said that a character shouldn’t be repeated).

So, your object contains the key propName with the value (which is a string) "John". If you understand this much, then great! We can move on to more stuff.

I assume you know how to access properties literally like someObj.propName. What I want you to understand is that propName is just a string. You could have named it Princess Bananahammock (with the space in the middle, yes!).

Instead of accessing properties of an object literally, you can access with a string. This is similar to indexing an array, but with a string.

someObj["propName"] // "John"

You could also substitute the string with a variable containing the string and it wouldn’t make a difference.

var p = "propName";
someObj[p]; // "John"

In your function, you’re declaring a variable s, and initializing it with the string value "prop". As you can notice, "prop" happens to be the first 4 letters of "propName". What propPrefix(str) does is “concatenate” s with str. “Concatenate” means join together (it’s a good piece of jargon to remember). So if I do "foo" + "bar", I get "foobar".

You’re doing propPrefix("Name"). So, you get "prop" + "Name", that is, "propName"!

In the last line, you’re doing exactly that! someProp contains the string "propName".



Thank you for your highly detailed feedback. I have now a better understanding about this example.