0

I am trying to create a function that uses the push() or pop() methods as arguments when it is called. I have a working a code but I noticed that I repeated myself a lot and I know that a function would help to improve my code quality, however, I have not been able to find a way to dynamically introduce the push() or pop() methods so I do not have to repeat the same lines of code when I want to do something similar.

This is the current working code (and this is similar to other lines):

pushBtn.addEventListener("click", () => {
    if (inputEl.value) {
        myEmojis.push(inputEl.value)
        inputEl.value = ""
    }
    render(myEmojis)
})

I created a function that I would pass the push() argument to but it doesn't work as expected. Here is the function I tried to create:

function modifyEmoji(action) {
    if (inputEl.value) {
        myEmojis.action(inputEl.value)
        inputEl.value = ""
    }
    render(myEmojis)
}

How I call the function:

pushBtn.addEventListener("click", () => {
    modifyEmoji(push)
})

This returns: "Uncaught TypeError: myEmojis.action is not a function"

Thanks in advance.

oldmanshola
  • 21
  • 1
  • 2
  • 1
    Try `myEmojis[action](inputEl.value)` and call with `modifyEmoji("push")` but also think about whether this is a good design choice... – ggorlen Jul 17 '21 at 21:15
  • Thanks ggorlen, but what do you mean by design choice? – oldmanshola Jul 17 '21 at 21:16
  • I mean just that: design choice. Do popular and standard libraries typically operate like this where the client can specify which method is called on an internal object? Probably not, because it's (potentially) very confusing and brittle. – ggorlen Jul 17 '21 at 21:17
  • 1
    Oh, I understand what you're saying. I am actually a beginner and just wanted to explore beyond the tutorial I was watching. Thanks though. – oldmanshola Jul 17 '21 at 21:21
  • 1
    Yes, it does actually. Thank you very much. – oldmanshola Jul 17 '21 at 21:26

1 Answers1

0

this line of code: myEmojis.action(inputEl.value) says that a funcation named "actions" is defined for object array, While this is not the case and so it causes the error