JavaScript: Accessing Object Properties with Variables

I’m seeking an explanation of the explanation in

I have no idea what is being explained below if someone could kindly re-word it? I understand the code and what it’s doing, I just don’t understand why.

“Another way you can use this concept is when the property’s name is collected dynamically during the program execution, as follows:”

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"

This is a toy example, which sometimes makes things harder to understand.

The big idea is that you can create a variable that holds the name of the property you want to access. Sometimes the value in that variable is built as your code is running.

Here is a different example:

// Here is an object
let someObj = {
  firstName: "John",
  lastName: "Smith",
  age: 34

// Here is a function that looks for the first or last name
//  I build a variable to hold the property string I want
function firstOrLast(myObj, whichName) {
  // Here is my variable... It should hold either
  //  "firstName" or "lastName"
  let thisName = whichName + "Name";
  // Here is me using the variable to
  //  find the property I want
  //  (i.e. the name I want)
  return myObj[thisName];

// Let's test the function
console.log(firstOrLast(someObj, "first"));
console.log(firstOrLast(someObj, "last"));

Thanks for writing that out! Your explanation is easier to digest

1 Like

I’m glad I could help! Good question.