bicycle4431
bicycle4431

Reputation: 82

Force function to do nothing if variable is undefined

The function below currently throws an error in the console because the variable is undefined if no query is appended to the URL. How can I make it do nothing in this case?

function getParamName(name, url) {
  return url ?? location.href.split(`?${name}=`)[1];
}

Upvotes: 1

Views: 381

Answers (3)

aswin putra
aswin putra

Reputation: 147

you can just do a null check on the function if the var is empty or not. So just check if the name is empty or not and run your code if not empty

Like this:

function getParamName(name, url) {
  if(name && url){
    return url ?? location.href.split(`?${name}=`)[1];
  }
}

Upvotes: 0

VLAZ
VLAZ

Reputation: 28970

Use URLSearchParams to parse the query string and use .get() to give you the value associated with a specific one. This will automatically handle the case where you have multiple query string parameters and if you try to get one that doesn't exist, it just returns null:

function getParamName(name, url) {
  return url ?? new URLSearchParams(document.location.search.substring(1)).get(name);
}

console.log( getParamName("foo") );

Upvotes: 0

user15023244
user15023244

Reputation:

Use the try-catch block to ignore errors

try {
  Block of code to try
}
catch(err) {
  Block of code to handle errors
} 

https://www.w3schools.com/js/js_errors.asp

Upvotes: 1

Related Questions