Object, the Basics

As we learned from the chapter about Data types, there are 7 data types in JavaScript. Six of them are called “primitive”, because their values contain only a single thing (string, number, boolean, symbol, null and undefined).

Object

In contrast, the 7th type, object, is used to store a collection of properties.

Objects in JavaScript are very powerful. Here, we'll only touch the very basics of this topic. We'll learn more about them in later parts of the tutorial.

Object literal syntax

Object is capable of storing multiple values as properties. A property is a key: value pair. It is very common to create an object using an object literal, by putting key:value pairs (separated with a comma) in {}:

let obj = {key1: value1, key2: value2};

where key is usually a string (also called a property name), and value can be any value such as an integer, a boolean, or even another object.

Example:

// an empty object
let obj = {};

// objects with key:value pairs
let fruits = {'apple': 3, 'pear': 2, 'orange': 10};

An object definition can span multiple lines:

let student = {
  name: "Bella,
  age: 10,
  "likes math": true     // multi-word property name must be quoted
};

In the student object, there are three properties:

  1. The first property has the name "name" and the value "Bella".
  2. The second one has the name "age" and the value 10.
  3. The last property has the name "likes math" and the boolean value true.

In object literal, if the property name is a string which is also a valid variable name, then the quotes can be omitted. See definition of student for example.

Property names that contain multiple words and spaces should be avoided in general. "likesMath" or "likes_math" are preferred property names. If you use spaces in a property name, then it must be quoted.

results matching ""

    No results matching ""