How I create an optional parameter

Asked

Viewed 95 times

0

How can I set the second "&& bonus2" parameter as optional ?

I want the ways to run if: (bonus1 && bonus2 == true) or (bonus1 == true)

It needs to be a parameter that if I put it in the accepted function and rotate, if I do not put I remain normal, it is not a default value.

function offersFixed(bonus1, bonus2, textValue ){
        if (bonus1 && bonus2 == true ){        

        var valide = document.getElementById("valideorNot");
        valide.setAttribute("class", "invalidPass")
        valide.textContent = "Oferta Inválida";

        var textId = document.getElementById("validateResult");
        var createText = document.createElement("h3");
        createText.textContent = textValue;
        textId.appendChild(createText);
                 
        
    }
}

  • If bonus2 is optional, it makes no sense (bonus1 && bonus2 == true)

  • If bonus2 is optional, why check it? Unless inside the if it will influence something. Then you should make another if inside the if.

  • Shouldn’t be an OR? if (bonus1 === true || bonus2)? Will only check bonus2 if bonus1 is not true.

1 answer

0


It seems to me that there are several possibilities here, but that you do not want to enter the if case bonus1 or bonus2 be false.

If bonus2 is optional, you can set its value to true by omission.

function offersFixed(bonus1, bonus2, textValue ){
  // se passar false para bonus2, entao vai ser false, senão será sempre true
  bonus2 = (bonus2 === false) ? false : true;
  if (bonus1 === true && bonus2){
  // ... etc

Optional parameters

A change to the code would be to move what is optional to the end of the parameter list. As it is now, case bonus2 is not present, you still have to pass a value, even if it is null, and the call goes like this

offersFixed(true, null, 'O valor de textValue');

If you change the function signature to

function offersFixed(textValue, bonus1, bonus2)

you’ll be able to call it that

offersFixed('O valor de textValue', true);

And you can use the code provided at the top of the reply to bonus2 always be true, except when you pass false. Thus.

offersFixed('O valor de textValue', true, false);

Browser other questions tagged

You are not signed in. Login or sign up in order to post.