FAQ: Objects - Bracket Notation

I did it the same way you did, except I used the propName variable instead of ‘Active Mission’.

console.log(spaceship[propName]);

I think that the purpose of the propName variable is to show that variables can be attached to the object, and will access the properties of the object, provided the variable you’re attaching matches a property inside the object (I hope that makes sense).

Possible usage? I guess maybe if you have some properties in an object which are long/overcomplex an you want an easy way to reference them, you can just make a new easy to remember variable an have it then reference that property, at least that’s what I think.

Hope this helps.

3 Likes

In JavaScript objects, all keys are data type, string. When given as a subscript to an object identifier the given string is looked up in the object keys list to acquire the value associated with the key.

obj = {
    foo: 'foo',
    bar: 'bar',
    faz: 'faz',
    baz: 'baz'
}
for (key in obj) {
    console.log(key, typeof key);
}
/*
   foo string
   bar string
   faz string
   baz string
<- undefined
*/
console.log(obj.hasOwnProperty('foo'))
/*
   true
<- undefined
*/

Variables are nothing more than names in an address book. They are essentially properties of the object scope (namespace) in which they are contained.

a = 'foo'
console.log(window.hasOwnProperty('a'))
/*
   true
<- undefined
*/
console.log(window['a'])
/*
   foo
<- undefined
*/
foo = 'a'
console.log(window[foo])
/*
    foo
<- undefined
*/

Notice how when given a string, a variable behaves the same way as the string it represents.

I was wondering why in the example given:

let returnAnyProp = (objectName, propName) =>
  objectName[propName];

console.log(returnAnyProp(spaceship, 'homePlanet'));

We don’t need to wrap the function inside of curly brackets like this:

let returnAnyProp = (objectName, propName) => {
  objectName[propName];
}
console.log(returnAnyProp(spaceship, 'homePlanet'));

Is this something I’ve missed in previous lessons or has this not been taught yet?

Its a shorthand, the mdn documentation has an example:

(param1, param2, …, paramN) => expression
// equivalent to: => { return expression; }

quite useful for functions with a single line body.

Ohh right, yeah now I remember thank you!

if I have this object:

let spaceship = {
  homePlanet: 'Earth',
  color: 'silver',
  'Fuel Type': 'Turbo Fuel',
  numCrew: 5,
  flightPath: ['Venus', 'Mars', 'Saturn']
};

then why can I do this:

let crewCount = spaceship.numCrew;

if you have to use bracket notation to access keys with numbers or special characters? how is this legal?

Hello, @izzykreiee.

The key you are referring to has no numbers or special characters. It’s simply a camelCased name. The value paired with the key is a number, but that has no bearing on a requirement to use bracket notation when referencing the key. In your example, 'Fuel Type' would require the use of bracket notation, but the remaining keys can all be accessed via . notation.

Also, there is no restriction regarding having a number in the name of a ‘key’ as long as it it a legal variable name.

let spaceship = {
homePlanet: 'Earth',
color: 'silver',
'Fuel Type': 'Turbo Fuel',
numCrew: 5,
num2ndCrew: 6, //key has a number in it
flightPath: ['Venus', 'Mars', 'Saturn']
};

console.log(spaceship.numCrew) // 5
console.log(spaceship["numCrew"]) // 5 (bracket notation works as well)
console.log(spaceship.num2ndCrew) // 6
console.log(spaceship["Fuel Type"]) // Turbo Fuel
console.log(spaceship."Fuel Type") // Syntax Error
1 Like

This is another one of those questions that makes no sense to me. I walk away more confused than when I started.

What is/was the point of the lesson question 2? All three of the following will give a green check and allow me to move on to the next lesson.

console.log(isActive);

console.log(spaceship['Active Mission']);

console.log([spaceship[propName]]);

I’ve read through the post above and see what the a couple people have figured out what they think the take away is. But why do it like this?

This exercise shows multiple ways we can solve this problem:

let isActive = spaceship['Active Mission'];

console.log(isActive);

console.log(spaceship['Active Mission']);

these two logs statements are nearly identical, except the first one does an intermediate step by creating a variable first.

same here:

let propName =  'Active Mission';

console.log(spaceship[propName]);

except this time we make the key/property value into a variable.

These concepts are needed for when we get to object looping section. You will see :slight_smile:

3 Likes

Ahhh, I see. Ok.

This is maybe something that should be pointed out in the lesson. I sometimes get the feeling that some of these lessons are like reading documentation that was written by engineers for engineers. That is to say written by someone that already knows the answer.

Thanks for the reply though.

the lesson even include an example of why variables might be useful:

let returnAnyProp = (objectName, propName) => objectName[propName];

returnAnyProp(spaceship, 'homePlanet'); // Returns 'Earth'

anyway, none of that matters. Well, matters a bit. Programming is mostly problem solving, the code is secondary objective and “easy” once you figured out how you solve the problem.

okay, that might not be entirely true in the beginning. You need to master certain concepts of programming of course, but the most important thing is to learn certain analytical skills/thinking steps. When you see instructions, take a moment to pause, analyse. Ask yourself critical question: what does this do? And why?

In the end, only you can teach yourself this. We can tell you about these thinking steps, but we can’t apply them for you

I see what you are saying. Sometimes, some of the lessons are confusing in how they end or how they are worded. It leaves me wondering, ‘did I do that correctly or did I just pass the test’

It’s a good course though and I am learning alot.

Asking yourself these questions is good. In real life, there isn’t a script that checks your code. You have to do this, so take your time to see if your code behaves as expected. Which means understanding requirements, check for edge cases. All these things are important to learn

I actually think its a good thing the lessons aren’t copy paste, this forces to think for yourself, which is so important.

if using variable name we have to use bracket notation instead of dot notation.
that would work,
console.log(spaceship[propName]);

I tried it this way, as I was wondering, how I can link step 1 and 2.

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

let propName = 'Active Mission';

// Write your code below

//1. Step

let isActive = spaceship['Active Mission'];

//2. Step
console.log(propName , isActive);

The output is: Active Mission true

Mentor’s please advise if I have understood it correctly?

Hi!
I tried it the same way, only difference is that I wrote isActive first:

console.log(isActive, propName);
In console it showed : true ‘Active Mission’

When I write as it shows in the solution provided in the right corner of the page, the console shows only ‘true’. It is confusing and I don’t understand why it works that way too and how to write it so that I can avoid errors in future, more complex code.

Just a correction that variables declared with the let and const keywords won’t actually become a property of their scope - the global object at least

1 Like

Yeah, there is a distinction. Trying to find a reasonable article on the subject.

hi guys,

I have a question.

What if i wanted to make the propName string of ‘Active Mission’ exactly that, just a string, and keep it unrelated to the ‘Active Mission’ belonging to the spaceship.

I’m not great with the terminology so i hope someone understands what I’m getting at. thanks!

To create a property name containing white space it needs to be written in quotes.

{
  'active mission': 'Earth Moon'
}