How do I create an optional parameter

0

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

I want if if it turns out the ways: (bonus1 & bonus2 == true) or (bonus1 == true)

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);
                 
        
    }
}
    
asked by anonymous 07.08.2018 / 02:50

1 answer

0

It seems to me that there are several possibilities here, but that you do not want to get in if bonus1 or bonus2 is false.

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

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 that made the code would move what is optional to the end of the parameter list. As it stands now, if bonus2 is not present, you still have to pass a value, even if it is null, and the call stays that way

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 way

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

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

offersFixed('O valor de textValue', true, false);
    
07.08.2018 / 12:36