DEV Community

Charlie @ 90-10.dev
Charlie @ 90-10.dev

Posted on • Originally published at 90-10.dev on

JavaScript Objects

In JavaScript, objects are a fundamental data type that represent a collection of properties. A property is a key-value pair, where the key is a string (or symbol), and the value can be any data type.

Creating Objects

There are 4 ways to create objects:

1. Object literal notation

We're creating an object called person with three properties: name and age:

let person = {
    name: 'Paul',
    age: 30
};

Enter fullscreen mode Exit fullscreen mode

2. Constructor function

A constructor function is a regular function that is called using the new keyword:

function Person(name, age) {
  this.name = name;
  this.age = age;
};

let person = new Person('Paul', 30);

Enter fullscreen mode Exit fullscreen mode

3. Object.create()

The Object.create() method can be used to create an object with a specified prototype object and properties:

const personPrototype = {
    sayHello: function() {
        console.log(`Hello ${this.name}`);
    }
};

let person = Object.create(personPrototype, {
    name: { value: 'Paul' },
    age: { value: 30 }
});
person.sayHello(); // prints: Hello Paul
Enter fullscreen mode Exit fullscreen mode

4. Class Notation

ES6 introduces classes that can be used to create objects. A class is a blueprint for creating objects with specific methods and properties:

class Person {
  constructor(name, age) {
    this.name = name;
    this.age = age;
  }
}

let person = new Person('Paul', 30);

Enter fullscreen mode Exit fullscreen mode

Accessing Properties

You can access an object's properties using dot notation or bracket notation:

let person = {
    name: 'Paul',
    age: 30,
    address: {
        city: 'London'
    }
};

console.log(person.name); // prints: Paul
console.log(person.address.city); // prints: London
console.log(person['age']); // prints: 30
Enter fullscreen mode Exit fullscreen mode

In this example, we access the firstName property using dot notation and the lastName property using bracket notation.

Modifying Properties

You can modify an object's properties by assigning a new value to the property:

let person = {
    name: 'Paul',
    age: 30
};

person.age = 40;

console.log(person.age); // prints: 40

Enter fullscreen mode Exit fullscreen mode

Adding Object Properties

You can add new properties to an object by assigning a value to a new key:

let person = {
    name: 'Paul',
    age: 30
};

person.twitter = '@90_10_dev';

console.log(person.twitter); // prints: @90_10_dev

Enter fullscreen mode Exit fullscreen mode

In this example, we add a new property called twitter to the person object.

Take Away

Objects are used extensively in Javascript - they are incredibly flexible and powerful, and they can be used to represent a wide variety of data structures, including arrays, linked lists, trees, and graphs.

Top comments (0)