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 trialVic Mercier
3,276 PointsWhich 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
231,269 PointsFor code formatting, you can use the instructions for code formatting in the Markdown Cheatsheet pop-up below the "Add an Answer" area. Or watch this video on code formatting.
But here's the difference between those statements:
-
namesActions.action()
this calls a method named "action" -
namesActions[action]()
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
3,276 PointsVic Mercier
3,276 PointsWhen using the bracket syntax the string you passed into the square bracket , it will cinvert that value to a property name?
Steven Parker
231,269 PointsSteven Parker
231,269 PointsThat's right. The value of the term in the brackets will be used as a property (or method) name.