In this video, the toy library’s lending desk starts recording loans. A loan links a toy to the member who has it, and each side needs to know about the other. You try the natural first attempt, setting only the toy’s borrower, and see Leo’s loans stay empty. Then you give the desk one lend() method that checks first and changes both sides.
Key Points
- A loan has two sides. Each toy gets a
borrower, which staysnulluntil someone takes it, and each member’s record gets aloansarray, empty at the start. A loan points the toy at the member and puts the toy in the member’s loans. - Setting one side doesn’t set the other. After
train.borrower = leo, the train says Leo has it, butleo.loans.lengthis still0, with no error and no warning. The borrower and the loans array are two separate properties on two separate objects. Nothing connects them except the code you write, unlike linked cells in a spreadsheet. - Adding the second line by hand everywhere doesn’t scale. Every script that lends would have to remember both lines, and one forgotten line brings the mismatch back.
- One method changes both sides. The desk’s
lend()finds the toy and the member, then checks before it changes anything. First, it keeps the desk’s age check: if the toy doesn’t suit the member, it says so and stops. Next, if the toy already has a borrower, it returns a message saying who has it and stops. - Only then does it change both sides. Only after those checks does it set the toy’s borrower and push the toy into the member’s loans. Then it returns the slip, with the due date from the policy.
- A refused loan changes nothing. When Maya asks for the train Leo already has, the check refuses the loan before any change, so Maya’s loans stay empty.
- The desk and the script share the objects. They reach the same toy and member objects by reference, so the script’s own names see what
lend()did. - The rule for a two-way link is that one method changes it. That method checks first and then changes both sides, and nothing else assigns a borrower or changes a member’s loans. Reading them is fine. JavaScript won’t stop other code from changing them. Both
borrowerandloansare ordinary properties, and any code that reaches these objects can set them. Keeping every change insidelend()is up to you.
The Final Code
toy.js, with one new line in the constructor, this.borrower = null;: