Search code examples
javascript

Passing a list of variables into a js function


Currently I have a bunch of variables that a dozen functions need access to. Here's a snippet, but the list is bigger than this.

let highSchoolChecked      = document.getElementById('highSchoolPack')     .checked;
let forRentChecked         = document.getElementById('forRentPack')        .checked;
let horseRanchChecked      = document.getElementById('horseRanchPack')     .checked;
let growingTogetherChecked = document.getElementById('growingTogetherPack').checked;
let cottageLivingChecked   = document.getElementById('cottageLivingPack')  .checked;
let snowyEscapeChecked     = document.getElementById('snowyEscapePack')    .checked;
let ecoLivingChecked       = document.getElementById('ecoLivingPack')      .checked;

There seems to be only two ways to get the functions to register them:

function function1() {
  let highSchoolChecked = document.getElementById('highSchoolPack').checked;
  let forRentChecked    = document.getElementById('forRentPack')   .checked;
  let horseRanchChecked = document.getElementById('horseRanchPack').checked;
}

// or
function function2( highSchoolChecked, forRentChecked, etc )

Is there an easy way to gain access to these where I just have to call one variable rather than 2 dozen?

e.g

function variablesList(){
  let highSchoolChecked      = document.getElementById('highSchoolPack')     .checked;
  let forRentChecked         = document.getElementById('forRentPack')        .checked;
  let horseRanchChecked      = document.getElementById('horseRanchPack')     .checked;
  let growingTogetherChecked = document.getElementById('growingTogetherPack').checked;
  let cottageLivingChecked   = document.getElementById('cottageLivingPack')  .checked;
  let snowyEscapeChecked     = document.getElementById('snowyEscapePack')    .checked;
  let ecoLivingChecked       = document.getElementById('ecoLivingPack')      .checked;
}

I tried function function1(variablesList) but it didn't seem to work. All the different functions are on different js files.


Solution

  • You can return an object of these values from a function, and call this function when you need these values. and because these functions are in different js files, you need to make sure the getVariableStates function is globally accessible and one solution to this is to attach it to the window global object.

    window.getVariableStates = function() {
        return {
            highSchoolChecked: document.getElementById("highSchoolPack").checked,
            forRentChecked: document.getElementById("forRentPack").checked,
            horseRanchChecked: document.getElementById("horseRanchPack").checked,
            // Add all other variables similarly
        };
    };
    

    When you need these values.

    function doSomething() {
        const states = getVariableStates();
        console.log(states.highSchoolChecked);
        console.log(states.forRentChecked);
    }