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"
.