1

sorry for my terrible english

I have a funtion like this

function E(element1, element2 = "yes", element3="no")
{
console.log(`E1: ${element1}\nE2: ${element2}\nE3: ${element3}`)
}

When I call this function, I only wanna change the thrid element and the second can stay the same Something like this E("test", stay, "yes")

Thanks

kuso.sama
  • 336
  • 1
  • 9
  • The parameters are not changing anything. They are defaulting values if a value is not given for the parameter. If you don't want something to "change", either pass it in, or take off the default value on the parameter list – Taplar Jul 29 '20 at 16:46

3 Answers3

2

The function E should already do what you are asking for.

The element2 = "yes" syntax is setting the default value of the element2 variable, when that variable is null. If you call the function just like your example E("test", stay, "yes"), the value of stay will not be changed, unless its value is null.

If you want to keep a null value, just remove the = "yes" part.

nip
  • 1,609
  • 10
  • 20
1

See this answer for some help: Is there a way to provide named parameters in a function call in JavaScript?

I rewrote your function as follows:

//In ES2015, parameter destructuring can be used to simulate named parameters.

function E(element1, {element2="yes", element3="no"}={}){
    console.log(`E1: ${element1}\nE2: ${element2}\nE3: ${element3}`);
}

// call E without a value for element2. The default is used.
E("test", {element3: "foo"})

Output:

E1: test

E2: yes

E3: foo

dmmfll
  • 2,666
  • 2
  • 35
  • 41
1

sugesstion

use key-value form when passing arguments to your funtion.
It will be lot more fexible.

   function E(variable)
    {
    
    console.log(`E1: ${variable.element1}\nE2: ${variable.element2}\nE3: ${variable.element3}`)
    }

E( {"element1" : "no","element2":"yes", "element3" : "no"} )
meBe
  • 154
  • 9