What is the use of this. Im confused

What is the use of this. Im confused
0

#1
var testObj = {
  12: "Namath",
  16: "Montana",
  19: "Unitas"
};

// Only change code below this line;
var playerNumber = 16;       // Change this Line
var player = testObj[playerNumber];   // Change this Line 

The output of this would be Montana. The question i have is why would you go through all this trouble instead of just doing this.

var player = testObj.16;   // Wouldnt this achive the same output????

#2

In JavaScript, identifiers cannot start with a number
16 is not a vaild identifier and therefore cannot be used to access object’s property using dot notation


#3

I’m not sure where you found this example, but it is not a good one. Generally speaking, you want to avoid naming variables with numbers. However, if you did it the way demostated here, testObj.16 would not work. The debugger will throw an error. If the object name is a number it must be in brackets [].
So this would work:

var testObj = { one:"Tom", two:"Jim", three:"John" };
var player = testObj.one;

But this would not:

var testObj = { 1:"Tom", 2:"Jim", 3:"John" };
var player = testObj.1;
//Error - Unexpected number

#4

I cleaned up your code.
You need to use triple backticks to post code to the forum.
See this post for details.


#5

I got the example from the free code camp lesson. The part I’m confused about is why would you need to go through all the trouble of using two variables to pass the objects parameter when you can access it directly?


#6

If your using static data like that example, you would access it directly. However in most applications you would be accessing the data in a dynamic way. In this case depending on what “player” is currently using the function. So you wouldn’t be setting the player number, but getting it as a function parameter or from somewhere else in your program. I believe the purpose of the example is to show you how to use a variable to access an object.


#7

ok I think I get it now. Just when I am starting to get this whole coding thing down I walk into something else that shows me how much I really dont know.

thank you for your help


#8

As @Josh5231 said, the point of this lesson is to teach you how to access an object property when that property is stored in a variable. You’re about to come up on a more complicated object challenge that many students struggle with because they didn’t pay attention to this challenge and incorrectly try to access an object property that is contained in a (argument) variable or simply have no idea how to do so.


#9

Thank you all for your help I really didnt want to move forward without completely understanding this lesson.