1

I have a problem to solve involving default parameters and object destructuring. I have an object 'product' with this shape:

{
     name: "Slip Dress",
     priceInCents: 8800,
     availableSizes: [ 0, 2, 4, 6, 10, 12, 16 ]
   }

Here is my code so far, but I am receiving an error that 'availableSizes' is not iterable. Can someone help me correct this code?

I have tried adjusting the default parameters in my function and I have moved my return statements to no avail.

function checkIfSizeIsAvailable(product = {availableSizes:[]}, size = 0) {
  // let availableSizes = product;
  let foundSize = "";
  for (let sizeCheck of product.availableSizes) {
    if (sizeCheck === size) {
      foundSize = size;
    }
  }
  if (foundSize === ""){
    return false;
  } else {
    return true;
  }
  //for (let i = 0; i < sizes.length; i++) {
  // return false;
}
1
  • There is no destructuring in your code. You just have a default parameter. Presumably you pass an actual value for product which doesn't have availableSizes Commented Jul 29, 2021 at 17:46

1 Answer 1

1

As VLAZ mentioned in a comment, you can pass an object without an availableSizes field and it'll cause that error.

Destructuring happens when your variables together form an object/array on the left-hand size of the assignment:

function checkIfSizeIsAvailable(product = {availableSizes:[]}, size = 0) {
  // ^ Because of the default parameter, product always exists
  // Now we actually destructure with a default value for missing fields
  const { availableSizes = [] } = product;
}

or more compact:

function checkIfSizeIsAvailable({ availableSizes = [] } = {availableSizes:[]}, size = 0) {

}

Mind that this does not defend against non-array values, or even falsy values. A user can pass { availableSizes: false } and your availableSizes would also be false.

Sign up to request clarification or add additional context in comments.

3 Comments

Or even more compact: function checkIfSizeIsAvailable({ availableSizes = [] } = {}, size = 0)
Also, the body of the function can be compacted to return availableSizes.includes(size)
That worked! Thanks for helping me solve this one.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.