JavaScript Default parameters

function makeShoppingList(item1=‘milk’, item2=‘bread’, item3=‘eggs’){
console.log(Remember to buy ${item1});
console.log(Remember to buy ${item2});
console.log(Remember to buy ${item3});
}
Is there any way to set value for item 3 or item 2 only without changing value for item 1 ???

Hello, and welcome to the forums!

It is possible, though it may not be the prettiest solution.

function makeShoppingList(item1 = 'milk', item2 = 'bread', item3 = 'eggs') {
  console.log(`Remember to buy ${item1}`);
  console.log(`Remember to buy ${item2}`);
  console.log(`Remember to buy ${item3}`);
}

makeShoppingList();
// Prints: 
// Remember to buy milk
// Remember to buy bread
// Remember to buy eggs

makeShoppingList(undefined, undefined, 'cheese');
// Prints: 
// Remember to buy milk
// Remember to buy bread
// Remember to buy cheese

By passing in undefined for the first 2 arguments the default values you supplied were maintained, and the 3rd could be changed.

1 Like

Thank you soo much for the help.
It solves the problem.
But I still wonder if there is a way to directly declare value for the 3rd item only.

The feature you are looking for is named/keyword arguments (as oppose to positional arguments), since es6 we simulate this feature somewhat:

but that is as close as we are going to get

The thing is when making a function, any value with a default parameter must be followed by other values with default parameters. So either change the order of the parameters so that you have non-default parameters first; or you can use some value like an empty string "", none, or null which acts like empty parameters depending on your convention.

Good luck :slightly_smiling_face:

This might be true, but in python we can do:

image

this way, we only have to provide the argument we want to change the default value of. I do sometimes miss this feature in other languages (like JavaScript).

But that didn’t worked for me because I tried using empty strings and it removes the default value from the result and prints the quotation only.

I think we can also do this in Java script if we declare items as a variable and change them later on.

No, JavaScript does not have named/keyword arguments support. We can only simulate this feature, see my earlier answer with stackoverflow link.

@stetim94

Yes, I am aware of that.

My point was that you can’t have

def example(a=3, b): #a default parameter followed by a non-default parameter
    print(a + b)

example(b=1) #doesn't work
example(1, 2) #doesn't work their

Default parameters must be followed by default parameters in the next argument index. But you can have non-default arguments of course followed by either.

def example(a, b=3): #works fine
  print(a + b)


example(5)
example(1, b=9)