Skip to content
Advertisement

Function default object, props with default values are undefined

I am working on a function and when I set all of the required inputs as object props and some of them with default values, those that I gave default values to are undefined.

Basically, I want to create some of the properties of the object required and others not.

The issue is that, if I provide a value to containerClassName for example, all of the props that have default values become undefined and I can’t figure out why?

This will log all default values, no problems

beforeAfterComparison()

This will log undefined for all of them

beforeAfterComparison({ containerClassName: "someClassName" })

function beforeAfterComparison(
  {
    containerClassName,
    beforeImageUrl,
    afterImageUrl,
    containerIndex,
    lineWidth,
    lineColor,
    circleDiameter,
    circleColor,
  } = {
    containerIndex: 0,
    lineWidth: 2,
    lineColor: "black",
    circleDiameter: 50,
    circleColor: "lightgray",
  }
) {
  console.log(containerIndex);
  console.log(lineWidth);
  console.log(lineColor);
  console.log(circleDiameter);
  console.log(circleColor);
}

beforeAfterComparison();
console.log("-------------------");
beforeAfterComparison({ containerClassname: "someClassName" });

I am expecting that in both cases I should get my default values.

Advertisement

Answer

I think the syntax is wrong. Try this,

 function beforeAfterComparison(
  {
    containerClassName,
    beforeImageUrl,
    afterImageUrl,
    containerIndex = 0,
    lineWidth = 2,
    lineColor = "black",
    circleDiameter = 50,
    circleColor = "lightgray",
  } = {}) {
  console.log(containerIndex);
  console.log(lineWidth);
  console.log(lineColor);
  console.log(circleDiameter);
  console.log(circleColor);
}
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement