"Passing a variable as an argument to a function in JavaScript

I've been working on setting up a basic loop of animation functions. Each function is stored in an array, and I have successfully logged out each object as a string upon click event. However, I'm encountering difficulties when trying to call the corresponding functions during that event.

One of my attempts led to an error message stating "nt[rt] is not a function".

arrAnimations[activeScene]() 

In my effort to resolve this issue, I explored various solutions from similar scenarios on stack overflow. One approach involved creating a helper function like the one below:

myFunction = function(){};   
   var arrAnimations = {italy: myFunction};

    
    arrAnimations['activeScene'](); //executes the function

I also experimented with another method, as shown here:

var tmp = arrAnimations[activeScene]
     window[tmp]

Below is the code snippet:


      
         var arrAnimations = ['italy', 'czech', 'russia']
        
      var activeScene = 0;

          document.getElementById('animate').addEventListener("click",  function incNumber() {
               if (activeScene < arrAnimations.length - 1) {
                activeScene++;
                } else if (activeScene == arrAnimations.length - 1) {
                 activeScene = 0;
             }
           
        })
          
           function italy() { console.log('italy') }

           function czech() { console.log('czech') }

            function russia() { console.log('russia') }
<div id="animate">Animate</div>

Answer №1

The array in this code snippet is unique because it stores the actual functions themselves, rather than just their names.

function italy()  { console.log('italy') }
function czech()  { console.log('czech') }
function russia() { console.log('russia') }

var arrAnimations = [ italy, czech, russia ]

To execute a function from the array, you can easily locate the item by its index and call it:

var activeScene = 0;
arrAnimations[activeScene]()

Demo using Stack Snippets

function italy()  { console.log('italy') }
function czech()  { console.log('czech') }
function russia() { console.log('russia') }

var arrAnimations = [ italy, czech, russia ]

var index = 0;

function callNextFunction() {
    index = index >= arrAnimations.length - 1 ? 0 : index + 1
    
    arrAnimations[index]()
}

var btn = document.getElementById('animate')
btn.addEventListener("click", callNextFunction)
<button id="animate">Animate</button>

Answer №2

Here is some advice on your commented out line:

console.log(arrAnimations[activeScene])

The issue here is that you are trying to call a method on an array, but the array only contains strings. To fix this, you should extract the string value from the array and then use it to call a method on the window object.

window[arrAnimations[activeScene]]();

To simplify your code and avoid using multiple if statements, you can consider using lambda functions. Here's an example for you to try:

<div id="animate">Animate</div>

<script>
    var arrAnimations = [
        () => console.log('italy'),
        () => console.log('czech'),
        () => console.log('russia')
    ]

    var activeScene = 0;

    document.getElementById('animate').addEventListener('click', () => {

        arrAnimations[activeScene]();

        activeScene++;
        activeScene = activeScene % arrAnimations.length;
    });
</script>

Answer №3

spain = () => console.log('spain')
germany = () => console.log('germany')
france = () => console.log('france') 

if Array of functions:

let arrCountriesAsFunctions = [ spain , germany , france];
arrCountriesAsFunctions.forEach(country => country())

if Array of Strings:

let arrCountriesAsStrings = [ 'spain' , 'germany' , 'france' ];
arrCountriesAsStrings.forEach(country => eval(country)())

use eval to execute a string as JavaScript code

Answer №4

Is this the desired outcome?

foo = () => console.log('foo')
bar = () => console.log('bar')
baz = () => console.log('baz')

fns = {
  foo,
  bar,
  baz
}

Object.keys(fns).forEach(fn => fns[fn]())

fns['foo']()
fns['bar']()

Please note that attempting to convert a string into a function in JavaScript is not possible:

let fn = () => {}
let foo = 'fn'
foo() // X
// foo is a string, not a function. It is merely coincidental that the string's content matches a function name.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Using my aspx page as the central point for my web application, incorporating HTML5 codes for development

I created an aspx file for my GUI, image buttons, and image slide shows using HTML5, CSS, and javascript. I finished the HTML5 part in the aspx file format within visual studio 2012. To standardize my GUI for all other web forms, I tried creating a new mas ...

What is the best way to initiate a fresh AJAX request whenever the submit button is pressed?

Every time the submit button is clicked on my form, a modal appears and gets filled with JSON data from the application /addresschecker. If I receive an error message with a code return number of 2003, it indicates an issue with the addresses provided. Oth ...

Enhancing Browser Experience: The correct method for dynamically adding an AngularJS controller through a Chrome Extension's Content

Currently, I am in the process of developing a Chrome extension using AngularJS. To attach a controller to the required DOM elements on a webpage, I have been utilizing the following content script code: setController() { if(this.setContollerConditio ...

Do not include any null or empty objects when assigning to an array in Mongoose

When using mongoose's find() or findOne() methods, the returned value will be [] and null, respectively, if the where conditions are not met. This can cause issues when assigning these values to an array. Currently, I am filtering out the null values ...

Looking to display parent and child elements from a JSON object using search functionality in JavaScript or Angular

I am trying to display both parent and child from a Nested JSON data structure. Below is a sample of the JSON data: [ { "name": "India", "children": [ { "name": "D ...

Attempting to enter text into a text field using Selenium

Trying to post a comment on an Instagram post using Selenium in Java. The Instagram Comment box is in a textArea. How can I successfully add a comment? My attempted solution was... WebElement cmdbox = driver.findElement(By.tagName("textarea")); ...

How to iterate through an array in jQuery/JavaScript and create variables in each loop?

I've been puzzled for a while now as to why this code snippet doesn't work as intended: if (longest.length >= 3) { for ( var i = 0; i < longest.length-1; i++) { var $last[i] = longest[i].splice(-1).toString(); //if ( $( $la ...

Protractor's browser.wait function is not functioning properly when conducting tests on a non-AngularJS website

I am currently working on testing a non-angular JS website using Protractor. Even though my test case passes successfully, I am looking to eliminate the sleep statement and replace it with either a wait or Expected condition in my test case. Here is a sni ...

Get data from ajax request in controller

I'm currently working with this JavaScript code snippet: var formData = new FormData($('#formSlip').get(0)); formData.append('myList', JSON.stringify(tests)); The variable tests holds a list of objects. I am making an AJAX PO ...

React Native (or React) utilizes separate TypeScript modules to detect and respond to style adjustments for dark mode

Objective: Add a dark mode feature to a react native application. A brief overview of the system: File structure: Profile.ts ProfileCss.ts constants.ts In my app, I've organized styles in separate .ts files and exported them as modules to keep them ...

Exploring z-indices in event bubbling

JSFiddle: https://jsfiddle.net/uLap7yeq/19/ Issue Let's examine a scenario where there are two elements, canvas and div, positioned in the same location using CSS. The div has a higher z-index compared to the canvas, but how can we make sure events ...

The onClick function is failing to work properly, and I need to pass the value of 'cid' based on the result of the button

Is it possible to pass the 'courseid' to local storage when a button is clicked? I am having trouble with onclick not working. How can I retrieve the relevant 'courseid' in the onclick function based on the button clicked? handleClick ...

Submitting a form in a Chrome packaged app

Exploring Chrome packaged apps for the first time and facing a common issue that involves two questions. Attempting to create a basic form to submit data to a server using Ajax and POST. However, running into the restriction of not being able to use inlin ...

Using Vue app and Javascript to dynamically add an object to an array based on a certain condition

I'm currently working on a restaurant menu project where each item is an object with properties such as name, id (which is autogenerated), quantity, and options. Each option includes size and price values nested within an array. My goal is to allow u ...

Creating an eternal loop within the useEffect hook in order to monitor the presence of a specific property within the window object

Upon loading, I need to verify if the window object has the property VL.refCode. My website utilizes viral loops, and the VL object is populated with the refCode property when a user registers. Initially, I used a for loop within a useEffect hook to deter ...

In what way does this operate in an asynchronously?

As a newcomer to node.js and asynchronous JS, I am grappling with interpreting it correctly. Specifically, I am trying to grasp the mechanics behind this snippet of code: var fs = require('fs') var filedir = process.argv[2] function doneReading ...

PHP - array_push function

Here's a function that I have: function push_to_array() { $array_of_data = func_get_arg(0); for($i = 1; $i < func_num_args(); ++$i){ $array_of_data[] = func_get_arg($i); } return $array_of_data; } You can use it with an e ...

Tips for achieving a slow scrolling effect similar to the one displayed on these websites

I've noticed smooth slow scrolling on various websites and have been searching for React or Vue plugins to achieve this effect. However, I am interested in learning how to implement it using vanilla JavaScript. Feel free to suggest plugins, libraries, ...

Is the toString() method explicitly invoked by Number() if the value is not of type number or string? (such as a function)

Looking for clarification on the behavior of parseInt() compared to the Number() constructor called as a function. I want to confirm if this is reliable and if there's an official reference to support it. Below is sample code: let adder = (function ...

Issue with JQuery's parentsUntil method when using an element as a variable not producing the desired results

I'm having trouble with a specific coding issue that can be best illustrated through examples: For example, this code snippet works as expected: $(startContainer).parents().each(function(index, parentNode) { if (parentNode.isSameNode(commonConta ...