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

Need more explanation for the nameActions[action]() trick :)

Hey Could you please explane more about this trick with nameActions[action]() Still kind of thinking how can we replace this:

if (button.textContent === 'remove') {
        nameActions.remove(ul, li);
} else if (button.textContent === 'edit') {
        nameActions.edit();
}  else if (button.textContent === 'save') {
    nameActions.save();
}

on this

const action = button.textContent;
nameActions[action]();

How does the method understand which statement and which function inside should be run?

Would like to practice more on it and have a link where I can read about it as well. Thanks in advance.

Marina.

1 Answer

Steven Parker
Steven Parker
231,007 Points

This works because you can access a method two ways. One way is the "dot notation" where you just attach the name of the method to the object using a period, like "nameActions.edit". The other way is the "bracket notation", where you use brackets around a string representing the method name like "nameActions["edit"]". Since the term in brackets is a string and not just a name, you can substitute a variable that contains the name, like "nameActions[action]".

So the clever programming technique here takes advantage of the fact that the legends on the buttons are exactly the same as the method names, and uses the button name strings to access the methods directly. Note that the exact match is necessary for this to work — for example, it would not work if the button legends showed the names in capital letters, or starting with a capital letter.

Does that clear it up?