Creating Objects

Grade 8, page 2 of 13. A one-minute read.

You create an object with curly braces { }. Inside, you write key: value pairs, separated by commas:

JavaScript
const phone = {
  brand: "Nova",
  model: "Spark",
  storageGB: 128,
  colors: ["black", "blue", "gold"],
  isWaterproof: false,
};

console.log(phone);

It prints

{
  brand: 'Nova',
  model: 'Spark',
  storageGB: 128,
  colors: [ 'black', 'blue', 'gold' ],
  isWaterproof: false
}

(Node prints short objects on one line and longer ones spread across several lines. Either way, it's the same object.)

A few rules:

  • Each key is followed by a colon :, then the value.
  • Properties are separated by commas. A comma after the last property is allowed (and helpful, because adding a new property later won't require touching the line above).
  • Values can be anything: strings, numbers, booleans, arrays, other objects, even functions.
  • Keys follow the same rules as variable names. If you really need a key with a space or a hyphen, wrap it in quotes: "favorite color": "green". But it's much easier to just use camelCase.

An empty object is simply {}.

Reading is step one

CurlyScript turns these notes into a game: short questions, an explanation after every answer, and a test at the end of each grade. Free, with nothing to sign up for.

Start learning