0

I'm still learning JavaScript. Not able to get past this:

  function Fruits(category, berries, notberries) {
      this.category = category;
      this.berries = [];
      this.notberries = [];
  }

  let f = new Fruits("fresh", ["strawberry", "raspberry"], ["apple", "mango"]);

  console.log(f); // Fruits {category: "fresh", berries: Array(0), notberries: Array(0)}

  f.category;  //"fresh"

  f.berries; //[]

Why is it not logging the values of berries and instead returning an empty array ?

1
  • 5
    By calling this.berries = []; you've declared berries' value as an empty array, regardless of the constructor's parameters Commented Feb 26, 2018 at 23:28

2 Answers 2

2

You need to assign the arguments to the proper attributes.

function Fruits(category, berries, notberries) {
  this.category = category;
  this.berries = berries;
  this.notberries = notberries;
}

let f = new Fruits("fresh", ["strawberry", "raspberry"], ["apple", "mango"]);

console.log(f); // Fruits {category: "fresh", berries: Array(0), 
f.category;
f.berries;

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

1 Comment

Which local variables? The parameters are local variables.
0

Nothing in your constructor ever assigns the parameter berries to the property this.berries (or copies its content); the same for notberries.

To assign:

function Fruits(category,berries,notberries) {
    this.category = category;
    this.berries = berries;          // ***
    this.notberries = notberries;    // ***
}

To copy (shallow, which is fine, these are arrays of strings):

function Fruits(category,berries,notberries) {
    this.category = category;
    this.berries = berries.slice();          // ***
    this.notberries = notberries.slice();    // ***
}

The difference is that if you assign, then the object has a reference to the array that was passed in, and so does the calling code; if the calling code modifies that array, it affects the object (since they share the array). If you copy the contents of the array, then the calling code and the object each have their own array, so changes to one don't affect the other.

Both can be correct, you just need to be aware of the distinction.

Comments

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.