JavaScript course Lesson 6 of 6

JavaScript from zero: pass the object

A function can take the object and read the fields it needs. price takes a drink and returns the label. The program prints latte $4.50.

Zoe is one of GoByte's characters. This post was drafted by AI agents in Zoe's voice, then fact checked, run and edited by the GoByte team.

Back to top

Once the drink is an object, functions should take the drink. They read the fields they need. Adding a field later does not mean threading a new argument through every call. price returns the label, the same text the method built.

Pass the object the function reads#

price does not close over a global item. It receives the object and reads name and cents. The caller chooses which object. That is the whole contract: an object with those properties. There is no class requirement. A misspelled property is undefined, and the label would show that, so a caller that cares should check. This program passes a latte and prints latte $4.50.

price reads the fields off the argument
  1. lattelabellatte $4.50
function price(item) {
  const frac = String(item.cents % 100).padStart(2, "0");
  return item.name + " $" + Math.floor(item.cents / 100) + "." + frac;
}

const latte = { name: "latte", cents: 450 };
console.log(price(latte));
latte $4.50

One argument, named fields#

price takes item and returns the label. The print is latte $4.50. A caller who passes the cents and the name in the wrong order cannot, because there is nothing to swap. There is one argument.

price(null) throws when it reads .cents. If a missing item is normal, check item == null first and return a value you chose, the way the Java lesson printed missing. If a missing item is a bug, the throw is the right signal. It points at price.

Methods and functions can share the work#

latte.label() is the method on the class. price(latte) is a function that takes the object. Use a method when the behavior belongs to the drink and uses this. Use a function when the same step should work for any object with name and cents, including a plain object that never went through new. Both are ordinary tools. Pick the one that keeps the call obvious.

Report a mistake

Your product here? Partner with us

Back to top

Discussion

No comments yet. Signed in GoByte members with a verified e-mail can join. Community guidelines

Reading is open to everyone. Commenting and voting need a GoByte account with a verified e-mail.