Home > Mobile >  JS pass default parameter as a variable that is defined inside that function?
JS pass default parameter as a variable that is defined inside that function?

Time:03-31

For example:

function mf(z, x c, lol = b) { // I need lol = azazaz
  let b = azazaz
  ...
}

Instead of lol = azazaz I obviously get b is not defined.

What I can do:

function mf(z, x, c, lol = "b") { //parameter lol is a string
  let b = azazaz
  lol = eval(lol) //now lol = azazaz
  ...
}

Also I can do this:

function mf(z, x, c, lol) { //parameter lol doesn't have default value
  b = azazaz
  if (lol == 0) {
    lol = b             //default value of lol = azazaz
  }
  ...
}

But the first one looks so non-professional, the second one has extra if statement which I also don't want. Is there any better way to do this?

CodePudding user response:

If defining the variable inside of the function isn't a hard requirement, you can probably leverage closures to do something like:

const b = 'azazaz';
function mf(z, x, c, lol = b) { 
 ...
}

Or, perhaps use 'OR' to avoid if

function mf(z, x, c, lol) { //parameter lol doesn't have default value
  let b = 'azazaz';
  lol = lol || b;
  ...
}

CodePudding user response:

If you need to change paramater and re-use it you must re-call the function like:

//every time function change lol and recall function
function mf(z, x, c, lol) {
  console.log('lol now is: '   lol);
  lol  ;
  if (lol <= 10) {
    mf(1, 2, 3, lol);
  }
}

mf(1, 2, 3, 0);

  • Related