Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community!

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript Node.js Basics 2017 Handling Errors in Node Organizing Your Code with require

Tomasz Grodzki
Tomasz Grodzki
8,130 Points

How to make the function that shows specified areas points?

I'm trying to write a function that takes from user two parameters.

First parameter is username, which is used to create an exact URL.

The second one is a topicArea. I want use a value of this parameter, to get to the topic area in JSON file.

Normally if I want to get to this topic I'm using a dot notation. E.g. profile.points.JavaScript. And it works just fine! So why if I'm using a parameter with a value that user passed it doesn't work? E.g. profile.points.variable(which is equal to 'JavaScript').

https://w.trhou.se/laik5yhlpy Problem occurs at line 39. And there's line 42 which works fine. Why line 39 doesn't show number of points just like line 42?

1 Answer

In javascript, you have dot notation (profile.points.variable) and bracket notation profile.points[variable] or profile.points['variable']

There's a subtle but important difference.

Dot notation is always static, they're always strings, never anything else, and definitely never variables. profile.points.variable is always interpreted as the "variable" property of the "points" property of the profile object. Note how only profile is a dynamic reference!

On the other hand, bracket notation is a lot more free, as these can be any type, including number and more importantly, variables.

You probably know that if array is an array, you can access items in the array by array[0], but never array.0 because array.0 doesn't exist (because this would be interpreted as array["0"]).

Similarly, profile.points.variable can be rewritten as profile["points"]["variable"], note the string literals here.

While what you really wanted was profile.points[variable] (well, that's what I assume you meant, anyway).