Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Is there a better way to write out long JavaScript "if" blocks

The following if-block seems really inefficient. I imagine there is a better way to do this.
This will be used to set parameters in a graphics library. eg camera position, objects position, and others.
Additionally, a generic solution is welcome.

const queryString = window.location.search;
const urlParameter = new URLSearchParams(queryString);
//this code is what my question is about V
if (urlParameter.has("a")) {
  a = parseInt(urlParameter.get("a"));
}
if (urlParameter.has("b")) {
  b = parseInt(urlParameter.get("b"));
}
if (urlParameter.has("c")) {
  c = parseInt(urlParameter.get("c"));
}
if (urlParameter.has("d")) {
  d = parseInt(urlParameter.get("d"));
}
//^

Note: I am fairly inexperienced with JavaScript, and mainly use it for hobby projects.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You can use an array with the input parameter names an iterate over it.

But since you cannot assign dynamic variable names in JavaScript, you will need to change your output slightly to use an object:

const allowedParameters = ['a', 'b', 'c', 'd'];

const parsedParameters = {};

allowedParameters.forEach((key)=> {
  if (urlParameter.has(key)) {
    parsedParameters[key] = parseInt(urlParameter.get(key));
  }
});

// To use the values just access each key in the parsedParameters object:

console.log(parsedParameters.a); 
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading