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! While you're at it, check out some resources Treehouse students have shared here.

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 DOM Scripting By Example Improving the Application Code Refactor 2: Readable Branching Logic

Vic Mercier
Vic Mercier
3,276 Points

Which method should I use in object . vs []

Why couldn't I do that: namesActions.action() instead of namesActionsaction;

What is the difference between both and when should I use one instead of the other.

I mean the square brackets vs the dot.

1 Answer

Steven Parker
Steven Parker
231,271 Points

For code formatting, you can use the instructions for code formatting in the Markdown Cheatsheet pop-up below the "Add an Answer" area. :arrow_heading_down:   Or watch this video on code formatting.

But here's the difference between those statements:

  • namesActions.action() :point_left: this calls a method named "action"
  • namesActions[action]() :point_left: this calls a method by the name that is stored in the string variable action

So if you had action = "test"; then doing the second one would be the same as namesActions.test().

Vic Mercier
Vic Mercier
3,276 Points

When using the bracket syntax the string you passed into the square bracket , it will cinvert that value to a property name?

Steven Parker
Steven Parker
231,271 Points

That's right. The value of the term in the brackets will be used as a property (or method) name.