-1

Topic: Objects SubTopic: Accessing Properties using Dot and Bracket Notation:

// object
let spaceship = {
  'Fuel Type': 'Turbo Fuel',
  'Active Duty': true,
  homePlanet: 'Earth',
  numCrew: 5
};

// writing function which access object properties using dot notation
let returnAnyProp1 = (objectName1,propName1) => objectName1.propName1;
console.log(returnAnyProp1(spaceship, 'homePlanet')); 
// Returns undefined

// directly accessing 
console.log(spaceship.'homePlanet')
// returns error: Unexpected String.

My question here is that when we are calling the function, it is returning spaceship.'homePlanet'. Right?

So my question is:

  1. Why is it searching for propName1 exactly and not the argument we are passing?
  2. Even if let's say it is searching for exactly propName1 then still it would mean spaceship.'propName1'. It should still return an error and not undefined right?

PS: I know we can use bracket notation here to solve this but I want to know what exactly am I missing in this concept that I am not understanding this.

  • If an object doesn't have a certain property, accessing it will give `undefined`. E.g. `const o = {}; o['does not exist'] === undefined` – ASDFGerte May 09 '21 at 01:18

2 Answers2

-1

You will want the indexer:

let returnAnyProp1 = (objectName1,propName1) => objectName1[propName1];

The way you have it means to actually access a property named propName1.

Your direct access pattern won't work.

Daniel A. White
  • 187,200
  • 47
  • 362
  • 445
-1

To be short, you can't use dot notation for this.

When you do

let returnAnyProp1 = (objectName1,propName1) => objectName1.propName1;

what it's doing is that it's checking the object for an attribute named "propName1". It's not passing the value of "propName1". What it's doing is it's physically checking the object to see if there's any attributes named exactly "propName1".

To fix this, you'll have to use bracket notation.

let returnAnyProp1 = (objectName1,propName1) => objectName1[propName1];
SatvikVejendla
  • 424
  • 5
  • 14