0

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?

2
  • function mf(z, x c, lol = 'azazaz') or when you call it like mf(z, x c, 'azazaz') ? Commented Mar 31, 2022 at 11:43
  • function mf(z, x c, lol = 'b') where 'b' contains the result of some actions inside of my function. The 'b' can be 'azazaz' or another value Commented Mar 31, 2022 at 11:53

2 Answers 2

1

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;
  ...
}
Sign up to request clarification or add additional context in comments.

2 Comments

lol = lol || b could also be written as lol ||= b. See the ||= documentation for details and compatibility.
@3limin4t0r makes sense, thanks for the suggestion :)
0

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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.