Build Records With Shorthand

In the last lesson, Tomás kept his lineup up to date with push(), shift(), and unshift(). That lineup held titles only. The friends’ watchlist holds full film records, and every new suggestion means typing another one, with a title, a running time, a genre, an empty seenBy list, and zero votes.

In this lesson, you’ll write a function that builds those records for Tomás, using the shorter ways JavaScript lets you write an object literal. You’ll be able to expand each short form into the long one in your head, name a property from data, and log variables so the output says which value is which. Start with the record Tomás types most often, a new film.

Build Records From Variables

When a function builds a record from its parameters, the long form repeats every name. You’ve met this before. In the first lesson, newEntry returned { title: title, votes: 0 } from an arrow function, with parentheses around the object so JavaScript didn’t read the braces as a body. You’ll see that arrow form again later in this lesson, for small one-line helpers.

Lucía suggests My Neighbor Totoro, an 86-minute animation. Here’s a makeFilm function that returns its record in the long form, where each of the first three property names is followed by the parameter that holds its value:

Language: JavaScript
function makeFilm(title, minutes, genre) {
  return {
    title: title,
    minutes: minutes,
    genre: genre,
    seenBy: [],
    votes: 0,
  };
}

console.log(makeFilm("My Neighbor Totoro", 86, "animation"));

The call returns a complete record, with nobody in seenBy yet and no votes:

Language: Program Output
{
  title: 'My Neighbor Totoro',
  minutes: 86,
  genre: 'animation',
  seenBy: [],
  votes: 0
}

The first three properties each repeat a name, as in title: title. When a property’s name matches a variable’s name, you can write the name once. This is a shorthand property. Save this version as films.js:

Language: JavaScript Filename: films.js
function makeFilm(title, minutes, genre) {
  return {
    title,
    minutes,
    genre,
    seenBy: [],
    votes: 0,
  };
}

console.log(makeFilm("My Neighbor Totoro", 86, "animation"));

Locked learning resources

Join us and get access to thousands of tutorials and a community of expert JavaScript developers.

Unlock This Lesson

Already a member? Sign-In

Locked learning resources

The full lesson is for members only. Join us and get access to thousands of tutorials and a community of expert JavaScript developers.

Unlock This Lesson

Already a member? Sign-In

Become a Member to join the conversation.