Skip to main content

Objects

In JavaScript, an object is an unordered collection of key-value pairs. Each key-value pair is called a property.

Create an empty object using the object literal notation:

let empty = {};

To create an object with properties, you use the key:value within the curly braces. The object data is public and the object is not an instance of a particular class.

// create a person object with properties 
let person = {
firstName: 'John',
lastName: 'Doe'
};

// store an object in variable person
const person = { name: 'Joe Brown', age: 36 }

// access properties with dot notation
let personAge = person.age


// To access properties, use either dot notation
console.log(person.firstName); console.log(person.lastName);

In the code above, person was declared as const but you can still mutate the object to which it refers; you cannot assign a different value to a const variable.

You can modify existing properties or add new properties.

// modify age property
person.age = 40

// add new property
person.salary = 90000

State and behavior

Objects have state and behavior:

  • state is provided by the properties
  • behavior is provided by methods
  • methods are accessed with the dot notation
  • every method is a function but not vice versa - can think of methods as functions accessed on an object with a dot.
// create an object with properties and a method
let harry = {
name: 'Harry Smith',
salary: 90000 ,
raiseSalary(percent) {
this.salary *= 1 + percent / 100
}
}

// raise harry's salary with a method
harry.raiseSalary(10)

Creating objects

JavaScript objects can be constructed with the new keyword:

The new operator creates a new empty object and then calls the constructor function. A constructor function by convention starts with a capital letter.

this points to the newly created object.

// function that constructs object
function Employee(name, salary) {
this.name = name
this.salary = salary
}

// create a new object
new Employee('Harry Smith', 90000)

add/delete properties

Unlike other languages, properties can be dynamically added to objects.

let person = {
firstName: 'John',
lastName: 'Doe'
};
// add age property to person object
person.age = 25;
// OR the bracket notation
person['age'] = 25;

Properties can be deleted with the delete keyword. To check if a property exists in an object, you use the in operator

// delete age property
delete person.age;

// check if a property exists
if ("age" in person) {
console.log("age in person");
}

Destructuring objects

In javascript, you can read an object's property and assign its value to a variable without duplicating the property name - with destructuring. Moreover, you can extract multiple properties from the same object in just one statement. Rather than:

let hero = {
name: 'Batman',
realName: 'Bruce Wayne'
};
let name = hero.name;
let realName = hero.realName;

with destructuring:

let hero = {
name: 'Batman',
realName: 'Bruce Wayne'
};
const { name, realName } = hero;

console.log(name);
console.log(realName);

yields:

bash
TERMINAL

Batman Bruce Wayne

destructuring ... rest

The rest(...) syntax can be used to collect remaining properties after destructuring. The destructuring extracts the property specified and the remaining properties are collected into rest.

const hero = {
name: 'Batman',
realName: 'Bruce Wayne',
company: 'WayneCorp'
};
const { name, ...rest } = hero;

console.log(rest);

yields:

bash
TERMINAL

{ realName: 'Bruce Wayne', company: 'WayneCorp' }

default values

If the destructured object doesn't have the property specified in the destructuring assignment, the variable is assigned with undefined. You can set a default value if the property doesn't exist in the destructured object.

const hero = {
name: 'Batman',
realName: 'Bruce Wayne'
};
// set a default value
const { enemies = ['Joker'] } = hero;

console.log(enemies)

bash
TERMINAL

[ 'Joker' ]

for/in

for/in can be used to enumerate individual properties of an object

  • works with any object after the in
  • runs once for each property of the object
  • if the object is null or undefined, skips the loop
for ( variable in object) {
loop-body
}

For example:

let person = {
firstName: 'John',
lastName: 'Doe',
ssn: '299-24-2351'
};

for(let prop in person) {
console.log(prop + ':' + person[prop]);
}

output:

bash
TERMINAL

firstName:John lastName:Doe ssn:299-24-2351