General function + parameter question


#1

This might be blindingly obvious, but why are parameters optional for some functions?


#2

Could you please provide a bit of background?

You could have default parameters, such as a default alive status for an animal object that would be set to true.


#3

I, too, have wondered when to use parameters. Case A takes newHeight as a parameter, but Case B is empty. How do you know if and when to include a parameter?

CASE A

var rectangle = new Object();
rectangle.height = 3;
rectangle.width = 4;
// here is our method to set the height
rectangle.setHeight = function (newHeight) {
  this.height = newHeight;
};
// help by finishing this method
rectangle.setWidth = function (newWidth) {
    this.width = newWidth;
};
  
// here change the width to 8 and height to 6 using our new methods
rectangle.setHeight(6);
rectangle.setWidth(8);

CASE B

var square = new Object();
square.sideLength = 6;
square.calcPerimeter = function() {
  return this.sideLength * 4;
};
// help us define an area method here
square.calcArea = function() {
    return this.sideLength * this.sideLength;
};

#4

You use parameters in situation A to set custom values, where in situation B you return a predefined value.

In classes, parameters can be used to set values (That's a large aspect), when functions without parameters can return values based on predefined information.

You couldn't calculate the area or perimeter of a square without first defining (or setting with a function) properties such as side length. :slightly_smiling: