How can I create functions to reduce redundancy in my code? [JS]

javascript create reusable function
you can define a function without calling it.
javascript function
write reusable javascript with functions
function code example
how to call a function inside a function in javascript
make your own javascript
reusable javascript components

My code is running well but I have repeated myself too much and the code will be too large considering that I have only handled a query for one collection. I have tried using a function to handle some of the code but it doesn't work as some variables are not accessible globally. Here is the code

 var markers = [];

        function addMarker(coords, content, animation){

            var marker = new google.maps.Marker({
                position:  coords,

                map: map,
                icon: icon = {
                    url : isBouncing ? red_icon : green_icon,
                    scaledSize: new google.maps.Size(40, 40), // scaled size

                },
                // IF THERE'S AN ERROR, BOUNCE IT
                animation: animation
            });

            var infoWindow = new google.maps.InfoWindow({
                content: content

            });


            marker.addListener('spider_click', function() {
                map.panTo(this.getPosition());
                infoWindow.open(map,marker);
            });
            oms.addMarker(marker); 

            markers.push(marker);
        }



      function clearMarkers() {
        setMapOnAll(null);
      }


      function deleteMarkers() {
        clearMarkers();
        markers = [];

      }



 db.collection('Nairobi').onSnapshot(function(snapshot) {

        snapshot.forEach(function(child){
                var name_loc = child.id;
                var loc = child.data().marker;
                var forward = child.data().ForwardPower;
                var reflected = child.data().ReflectedPower;

                var ups = child.data().UPSError;
                var upsDesc = child.data().UPSDesc;
                var trans = child.data().TransmitterError;
                var transDesc = child.data().TransDesc;
                 var kplc = child.data().KPLC;
                var kplcDesc = child.data().KPLCDesc;
                var sat = child.data().SatelliteReceiver;
                var satDesc = child.data().SatDesc;


                       if(ups === true && trans ===true && sat ===true && kplc ===true){
                        isBouncing = true;
                    addMarker(
                        {lat: loc.latitude, lng: loc.longitude },
                        '' +
                        '<div id="iw-container">' +
                        `<div class="iw-title"> ${name_loc}</div>` +
                        '<div class="iw-content">' +
                        "<br/>"
                        +  `<p> UPSError: ${upsDesc} </p>`
                        +  `<p> SatelliteReceiver: ${satDesc} </p>` 
                        +  `<p> KPLC: ${kplcDesc} </p>`
                         +  `<p> TransmitterError: ${transDesc} </p>`

                        +  '</div>' +
                        '<div class="iw-bottom-gradient"></div>' +
                        '</div>'


                        ,google.maps.Animation.BOUNCE
                    );
                }   


                  else if(ups === false && trans ===true && sat ===true && kplc ===true){
                        isBouncing = true;
                    addMarker(
                        {lat: loc.latitude, lng: loc.longitude },
                         '' +
                        '<div id="iw-container">' +
                        `<div class="iw-title"> ${name_loc}</div>` +
                        '<div class="iw-content">' +
                        "<br/>"

                        +  `<p> SatelliteReceiver: ${satDesc} </p>` 
                        +  `<p> KPLC: ${kplcDesc} </p>`
                         +  `<p> TransmitterError: ${transDesc} </p>`

                        +  '</div>' +
                        '<div class="iw-bottom-gradient"></div>' +
                        '</div>'


                        ,google.maps.Animation.BOUNCE
                    );
                } 



               else if(ups === true && trans ===false && sat ===true && kplc ===true){
                    isBouncing = true;
                    addMarker(
                        {lat: loc.latitude, lng: loc.longitude },
                         '' +
                        '<div id="iw-container">' +
                        `<div class="iw-title"> ${name_loc}</div>` +
                        '<div class="iw-content">' +
                        "<br/>"
                        +  `<p> UPSError: ${upsDesc} </p>`
                        +  `<p> SatelliteReceiver: ${satDesc} </p>` 
                        +  `<p> KPLC: ${kplcDesc} </p>`


                        +  '</div>' +
                        '<div class="iw-bottom-gradient"></div>' +
                        '</div>'


                        ,google.maps.Animation.BOUNCE
                    );
                }


               else if(ups === false && trans ===false && sat ===false && kplc ===false){
                    isBouncing = false;
                    addMarker(
                        {lat: loc.latitude, lng: loc.longitude },


                        '<div id="iw-container">' +
                        `<div class="iw-title"> ${name_loc}</div>` +
                        '<div class="iw-content">' +
                        "<br/>"
                        +  `<h2> Running well </h2>` 

                        +  '</div>' +
                        '<div class="iw-bottom-gradient"></div>' +
                        '</div>'

                    );
                }


                console.log(child.id, child.data());
            });


                 snapshot.docChanges().forEach((change) => {

                 if (change.type === "modified") {

                    deleteMarkers();
                    snapshot.forEach(function(child){

      /***************************REDUNDANT CODE****************************************/
                var name_loc = child.id;
                var loc = child.data().marker;
                var forward = child.data().ForwardPower;
                var reflected = child.data().ReflectedPower;

                var ups = child.data().UPSError;
                var upsDesc = child.data().UPSDesc;
                var trans = child.data().TransmitterError;
                var transDesc = child.data().TransDesc;
                 var kplc = child.data().KPLC;
                var kplcDesc = child.data().KPLCDesc;
                var sat = child.data().SatelliteReceiver;
                var satDesc = child.data().SatDesc;


                       if(ups === true && trans ===true && sat ===true && kplc ===true){
                        isBouncing = true;
                    addMarker(
                        {lat: loc.latitude, lng: loc.longitude },
                        '' +
                        '<div id="iw-container">' +
                        `<div class="iw-title"> ${name_loc}</div>` +
                        '<div class="iw-content">' +
                        "<br/>"
                        +  `<p> UPSError: ${upsDesc} </p>`
                        +  `<p> SatelliteReceiver: ${satDesc} </p>` 
                        +  `<p> KPLC: ${kplcDesc} </p>`
                         +  `<p> TransmitterError: ${transDesc} </p>`

                        +  '</div>' +
                        '<div class="iw-bottom-gradient"></div>' +
                        '</div>'


                        ,google.maps.Animation.BOUNCE
                    );
                }   




                else if(ups === false && trans ===true && sat ===false && kplc ===true){
                    isBouncing = true;
                    addMarker(
                        {lat: loc.latitude, lng: loc.longitude },
                         '' +
                        '<div id="iw-container">' +
                        `<div class="iw-title"> ${name_loc}</div>` +
                        '<div class="iw-content">' +
                        "<br/>"

                        +  `<p> KPLC: ${kplcDesc} </p>` 
                        +  `<p> TransmitterError: ${transDesc} </p>`

                        +  '</div>' +
                        '<div class="iw-bottom-gradient"></div>' +
                        '</div>'


                        ,google.maps.Animation.BOUNCE
                    );
                }

                else if(ups === true && trans ===false && sat ===true && kplc ===false){
                    isBouncing = true;
                    addMarker(
                        {lat: loc.latitude, lng: loc.longitude },
                         '' +
                        '<div id="iw-container">' +
                        `<div class="iw-title"> ${name_loc}</div>` +
                        '<div class="iw-content">' +
                        "<br/>"

                        +  `<p> UPSError: ${upsDesc} </p>` 
                        +  `<p> SatelliteReceiver: ${satDesc} </p>`

                        +  '</div>' +
                        '<div class="iw-bottom-gradient"></div>' +
                        '</div>'


                        ,google.maps.Animation.BOUNCE
                    );
                }

                else  if(ups === true && trans ===false&& sat ===false && kplc ===false){
                    isBouncing = true;
                    addMarker(
                        {lat: loc.latitude, lng: loc.longitude },
                        '' +
                        '<div id="iw-container">' +
                        `<div class="iw-title"> ${name_loc}</div>` +
                        '<div class="iw-content">' +
                        "<br/>"

                        +  `<p> UPSError: ${upsDesc} </p>` 

                        +  '</div>' +
                        '<div class="iw-bottom-gradient"></div>' +
                        '</div>'


                        ,google.maps.Animation.BOUNCE
                    );
                }

                else if(ups === false && trans ===true && sat ===false && kplc ===false){
                    isBouncing = true;
                    addMarker(
                        {lat: loc.latitude, lng: loc.longitude },
                        '' +
                        '<div id="iw-container">' +
                        `<div class="iw-title"> ${name_loc}</div>` +
                        '<div class="iw-content">' +
                        "<br/>"

                        +  `<p> TransmitterError: ${transDesc} </p>` 

                        +  '</div>' +
                        '<div class="iw-bottom-gradient"></div>' +
                        '</div>'


                        ,google.maps.Animation.BOUNCE
                    );
                }

                console.log(child.id, child.data());
            });

          }
       });

     })

And also is there a better way to handle those IF Statements to make my code more cleaner.


Here is the way you can make. Also, I created getHtml function to get the HTML. Add condition for other to use the getHtml for other like upsError

var markers = [];

function addMarker(coords, content, animation) {

    var marker = new google.maps.Marker({
        position: coords,

        map: map,
        icon: icon = {
            url: isBouncing ? red_icon : green_icon,
            scaledSize: new google.maps.Size(40, 40), // scaled size

        },
        // IF THERE'S AN ERROR, BOUNCE IT
        animation: animation
    });

    var infoWindow = new google.maps.InfoWindow({
        content: content

    });


    marker.addListener('spider_click', function () {
        map.panTo(this.getPosition());
        infoWindow.open(map, marker);
    });
    oms.addMarker(marker);

    markers.push(marker);
}


function clearMarkers() {
    setMapOnAll(null);
}


function deleteMarkers() {
    clearMarkers();
    markers = [];

}

function getHtml(name_loc,data) {
    return '' +
                        '<div id="iw-container">' +
                        `<div class="iw-title"> ${name_loc}</div>` +
                        '<div class="iw-content">' +
                        "<br/>"

                        +
                        `<p> TransmitterError: ${data} </p>`

                        +
                        '</div>' +
                        '<div class="iw-bottom-gradient"></div>' +
                        '</div>'
}


function calculateEachData(snapshot,child){
    /***************************REDUNDANT CODE HERE****************************************/
                var name_loc = child.id;
                var loc = child.data().marker;
                var forward = child.data().ForwardPower;
                var reflected = child.data().ReflectedPower;

                var ups = child.data().UPSError;
                var upsDesc = child.data().UPSDesc;
                var trans = child.data().TransmitterError;
                var transDesc = child.data().TransDesc;
                var kplc = child.data().KPLC;
                var kplcDesc = child.data().KPLCDesc;
                var sat = child.data().SatelliteReceiver;
                var satDesc = child.data().SatDesc;


                if (ups === true && trans === true && sat === true && kplc === true) {
                    isBouncing = true;
                    addMarker({
                            lat: loc.latitude,
                            lng: loc.longitude
                        },
                        '' +
                        '<div id="iw-container">' +
                        `<div class="iw-title"> ${name_loc}</div>` +
                        '<div class="iw-content">' +
                        "<br/>" +
                        `<p> UPSError: ${upsDesc} </p>` +
                        `<p> SatelliteReceiver: ${satDesc} </p>` +
                        `<p> KPLC: ${kplcDesc} </p>` +
                        `<p> TransmitterError: ${transDesc} </p>`

                        +
                        '</div>' +
                        '<div class="iw-bottom-gradient"></div>' +
                        '</div>'


                        , google.maps.Animation.BOUNCE
                    );
                } else if (ups === false && trans === true && sat === false && kplc === true) {
                    isBouncing = true;
                    addMarker({
                            lat: loc.latitude,
                            lng: loc.longitude
                        },
                        '' +
                        '<div id="iw-container">' +
                        `<div class="iw-title"> ${name_loc}</div>` +
                        '<div class="iw-content">' +
                        "<br/>"

                        +
                        `<p> KPLC: ${kplcDesc} </p>` +
                        `<p> TransmitterError: ${transDesc} </p>`

                        +
                        '</div>' +
                        '<div class="iw-bottom-gradient"></div>' +
                        '</div>'


                        , google.maps.Animation.BOUNCE
                    );
                } else if (ups === true && trans === false && sat === true && kplc === false) {
                    isBouncing = true;
                    addMarker({
                            lat: loc.latitude,
                            lng: loc.longitude
                        },
                        '' +
                        '<div id="iw-container">' +
                        `<div class="iw-title"> ${name_loc}</div>` +
                        '<div class="iw-content">' +
                        "<br/>"

                        +
                        `<p> UPSError: ${upsDesc} </p>` +
                        `<p> SatelliteReceiver: ${satDesc} </p>`

                        +
                        '</div>' +
                        '<div class="iw-bottom-gradient"></div>' +
                        '</div>'


                        , google.maps.Animation.BOUNCE
                    );
                } else if (ups === true && trans === false && sat === false && kplc === false) {
                    isBouncing = true;
                    addMarker({
                            lat: loc.latitude,
                            lng: loc.longitude
                        }, getHtml(name_loc,upsDesc), google.maps.Animation.BOUNCE
                    );
                } else if (ups === false && trans === true && sat === false && kplc === false) {
                    isBouncing = true;
                    addMarker({
                            lat: loc.latitude,
                            lng: loc.longitude
                        },getHtml(name_loc,transDesc), google.maps.Animation.BOUNCE
                    );
                }


                console.log(child.id, child.data());
}
function childSanp(snapshot) {
    snapshot.forEach(function (child) {
        calculateEachData(snapshot,child)
    });
}

function docSnap(snapshot) {
    snapshot.docChanges().forEach((change) => {
        if (change.type === "modified") {
            deleteMarkers();
            snapshot.forEach(function (child) {
                calculateEachData(snapshot,child)
            });

        }
    });
}

db.collection('Nairobi').onSnapshot(async function (snapshot) {

    await childSanp(snapshot)
    await docSnap(snapshot)

})

Functions — reusable blocks of code, Pretty much anytime you make use of a JavaScript structure that The JavaScript language has many built-in functions to allow you to do� I do not see any redundancy, except for the nameString line. I do however find useless code: the nameString variable belongs to the anonymous function created on line 2. Each run of the anonymous functions used on the .each() call is tested, and in case it passes any of the conditions, nameString gets set.


Create a function to create HTML content and pass necessary variables/placeholders to generate the content.

Use string ``to create an entire HTML string as follows.

<div id="iw-container"> <div class="iw-title"> ${name_loc}</div> <div class="iw-content"> <p> UPSError: ${upsDesc} </p> <p> SatelliteReceiver: ${satDesc} </p> <p> KPLC(: ${kplcDesc} </p> <p> TransmitterError: ${transDesc} </p> </div> <div class="iw-bottom-gradient"></div> </div>

JavaScript best practices, None of these make much sense — good variable and function names should be If you have global variables or functions in your code, scripts included after yours that Y9fu_cQ', /* The volume increase/decrease in percent and the volume� The reduce() method reduces the array to a single value. The reduce method executes a provided function for each value of the array (from left-to-right). The return value of the function is stored in an accumulator (result/total). Note: reduce does not execute the function for array elements without values.


Use nested if statements. As you say, the code is presently too long. A month or an year from now, you won't remember what happens where without constantly scrolling through it all.

Use a couple of variables.

if( ups == true ){
   if( trans == true ){
      bBouncing = true;
      ...
   }else{ // trans == false
      ...
}else{ // ups == false
   bBouncing = false;
   ...
} // End of all if's

addMarker(
   ...
   ,(bBouncing ? google.maps.Animation.BOUNCE : google.maps.Animation.NONE)

Practical Ways to Write Better JavaScript, In other words, if you create a function foo that takes a number: Aside from the overhead of adding types to your code, there are zero downsides to As you can see, the for-loop doesn't prevent me from doing it the right way, is both redundant and defeats the purpose of our ultimate goal: saving time. My point is that the Reduce Method In JavaScript gives you a mini CodePen where you can write whatever logic you want. It will repeat the logic for each amount in the array and then return a single value. The thing is, you don’t always have to return a single value. You can reduce an array into a new array.


Modern Javascript Techniques. Clean and scalable syntax in pursuit , Setting the standard with V8 is how Node.js was subsequently built. It may seem redundant at first, but commenting on code as best as possible will Performance is reduced due to function execution causing JavaScript to search through At this point, a lot of benefits can be gained from creating new� Software developers should strive to reduce code redundancy in their applications. You rarely need to create two elements that perform that same function. If a program looks for a keyboard input, for example, there should be only one routine to gather that input.


Routing, The following code is an example of a very basic route. This method is used for loading middleware functions at a path for all request methods. at a single location, creating modular routes is helpful, as is reducing redundancy and typos. If you write unit tests for your code, you’ll find it simpler to test the functions you call with .map(), .reduce(), or .filter(). All you have to do is provide inbound data for the function and


Don't repeat yourself, Don't repeat yourself is a principle of software development aimed at reducing repetition of software patterns, replacing it with abstractions or using data normalization to avoid redundancy. The DRY principle is stated as "Every piece of knowledge must have a single, They apply it quite broadly to include " database schemas, test plans, the build� Computer programs can become long, unwieldy and confusing without special mechanisms for managing complexity. This lesson will show you how to reuse parts of your code by writing Functions and break your programs into Modules, in order to keep everything concise and easier to debug. Being able to remove a single dysfunctional module can save