0

Is there a better way to add a default value to a Function object?

 function CountOfFruit(bowl){
    this.strawberries = bowl.strawberries
    this.blueberries = bowl.blueberries
    
   if (bowl.strawberries == ""){
     this.strawberries = "there is none"
   }
 }
fer.trecool
  • 71
  • 1
  • 2
  • 9
  • `this.strawberries = bowl.strawberries == "" ? "there is none" : bowl.strawberries;`??? You could do this in one line using the ternary operator. Or perhaps a default object? - [set-default-value-of-javascript-object-attributes](https://stackoverflow.com/questions/6600868/set-default-value-of-javascript-object-attributes) – Ryan Wilson Sep 29 '22 at 20:07
  • Does this answer your question? [How to get value from Object, with default value](https://stackoverflow.com/questions/9003999/how-to-get-value-from-object-with-default-value) – A_A Sep 29 '22 at 20:09

1 Answers1

2

Yes, you can write something like:

function CountOfFruit(bowl){
    this.strawberries = bowl.strawberries || "there is none";
    this.blueberries = bowl.blueberries || "there is none";
}

In that way, if one of the attributes is null or an empty string, the default value will be used.

Jérémie Boulay
  • 400
  • 4
  • 13