Utilizing Javascript to export modules and call multiple functions simultaneously

Is there a way to automate the calling of all functions within a module instead of individually selecting each one?

For instance:

bettermovies.js

module.exports={
    printAvatar: function(){
        console.log("Avatar");
    },

    printLord: function(){
        console.log("Lord of the Rings");
    },

    printGod: function(){
        console.log("God Of War");
    },
    favMovie: "Return of the King"
}

betterindex.js:

var movies=require('./bettermovies');
movies.printAvatar();
movies.printLord();
console.log(movies.favMovie);

I am wondering if there's a more efficient method, especially when dealing with a large number of movie functions in .js. It could become quite cumbersome to call each function manually rather than having a single function to handle them. This also brings up another question - how would you exclude certain functions from being called if you had, let's say, 100 of these print"movie" functions and wanted to skip 3 particular ones?

Appreciate your insights!

Answer №1

To loop through the movies object after requiring it, you can use a method like this:

for (var key in movies) {
    // Check if the property is a function and call it if true
    if (typeof movies[key] === 'function') {
        movies[key]();
    } else {
        console.log(movies[key]);
    }
}

Answer №2

I have recently created a jsfidde that could potentially help you with your issue. The code provided below iterates through an object and calls any functions it encounters.

var a = {
    printAvatar: function(){
        console.log("Avatar");
        $("body").append("Avatar <br/>");
    },

    printLord: function(){
        console.log("Lord of the Rings");
        $("body").append("Lord of the Rings <br/>");
    },

    printGod: function(){
        console.log("God Of War");
        $("body").append("God Of War <br/>");
    },
    favMovie: "Return of the King"
}

for(x in a){
    if(typeof a[x] == "function"){ // Only if function.
        a[x]();
    }
}

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

Show the text from the chosen option using jQuery with a button

Hey everyone, I have a question regarding a coding issue I'm facing. In this problem, I am unable to display the text from the selected option when I click the order button. The desired result is to show the selected option that I choose and display i ...

Basic selection menu layout

I have put together a basic menu for my WordPress site without relying on classes or IDs: <div class="main-menu"> <nav> <ul> <li> <a href="#" class="menu-link">home</a> ...

A Firefox Browser View of a Next.js and Tailwind Website magnified for closer inspection

After creating a website using Next.js and Tailwind CSS, I noticed that the site is appearing zoomed in when viewed in Firefox. However, it looks fine in all other browsers. When I adjust the screen to 80%, the website displays correctly in Firefox. What ...

Angular 12 - Encountering an issue with undefined properties when trying to access 'values'

Currently in the process of upgrading Angular Version from 8 to 12. Successfully made the upgrade from 8 to 11 without any issues. However, upon updating Angular to version 12, encountered an error stating "loadComponent TypeError: Cannot read propert ...

Tips for signaling to an AngularJS form that the input value has been altered

I developed a sign up form using angularjs. The submission process is functioning correctly. Now, I want to implement validation to check if the email provided is already registered. If it exists, display an error message indicating that the email is alrea ...

How can I send a jQuery ajax request with multiple custom headers?

I am facing an issue with my basic ajax request as I am trying to include a custom header using the following code: _auth=1,[my_apikey], Interestingly, when I make the same request using Postman, I receive a valid JSON response. However, when I attempt t ...

`Javascript framework suggests ajax navigation as the preferred method`

What is the best way to handle ajax navigation using jQuery? I have recently experimented with a simple jQuery ajax code to implement ajax-based navigation for all the links on a webpage. $('a').click(function(e){ e.preventDefault(); ...

jQuery random generator for creating two-dimensional arrays

Why do all rows always have the same numbers? They should be populated with random numbers. Also, how can I fix this issue? I remember seeing a solution here before but now I can't seem to locate it. var mapSizex = 5; var mapSizey = 6; var mapArray ...

Using Javascript to dynamically add SVGs from an array

Having issues with displaying SVG images in a quiz I'm building. I have a folder full of SVGs that correspond to each multiple choice option, but I can't seem to get the pathway right for them to show up properly. I've tried using template l ...

Console displays null as the attribute value

When I check the console, I notice that the data-postid attribute is displaying 'null'. What could be causing this issue? I would like to view the data-id in the console when clicking on the button with the id modal-save. I have reviewed my cod ...

Methods for hiding and showing elements within an ngFor iteration?

I am working on an ngFor loop to display content in a single line, with the option to expand the card when clicked. The goal is to only show the first three items initially and hide the rest until the "show more" button is clicked. let fruits = [apple, o ...

Utilizing One-to-Many Microphone Streaming Technology

I'm looking to create a unique one-to-many microphone streaming system where a user can record from their microphone and others can listen in. I also need to be able to record the microphone session. Would it be better to use WebRTC for client commun ...

I attempted to craft a toggle button by applying and removing an active class that I had previously designed, but unfortunately, it did not function as intended

Every time I click on a button, I keep encountering this error message. I am certain that my selector is correct, but I can't seem to figure out why I'm getting the Uncaught TypeError: Cannot read property 'classList' of undefined at HT ...

Exploring the wonders of useState in React/JavaScript - a comprehensive guide

I encountered an issue while attempting to map an API request from a useState hook. The fetch operation functions correctly and returns an array of objects that I then assign to my useState variable. Subsequently, when I try to map over the useState varia ...

What is the best way to position my Jchartfx area graph below my gridview?

When my page loads, the graph appears like this. It consistently shows up in the top left corner even though it should be positioned underneath the grid view as intended. var chart1; function createGraph(mpy) { if (mpy == undefined) mpy = 12.00; ch ...

Minimize the entire project by compressing the .css, .js, and .html files

After recently incorporating Grunt into my workflow, I was thrilled with how it streamlined the process of minifying/concatenating .css files and minifying/uglify/concatenating .js files. With Grunt watch and express, I was able to automate compiling and ...

CreateAsyncModule using an import statement from a variable

When trying to load a component using defineAsyncComponent, the component name that should be rendered is retrieved from the backend. I have created a function specifically for loading the component. const defineAsyncComponentByName = (componentName: strin ...

Combining a group of JavaScript objects

I am facing a challenge with my collection as I need to perform aggregation using only JavaScript. I have attempted various approaches utilizing the Lodash library but unfortunately, I have not been successful. If you could provide me with some guidance on ...

Unable to access MongoDB documents using NodeJS/Express

I can't seem to figure out why I am not receiving any results from a GET call I am testing with Postman. Let's take a look at my server.js file: const express = require("express"); const mongoose = require("mongoose"); const ...

Is it possible for parameters to still be filled even when they start off empty

Currently, I am enrolled in a javascript course and struggling to comprehend how the parameter in my example below is populated with the "correct stuff" without actually calling the function with a corresponding element? success: function(result) { ...