JavaScript Objects with Examples

JavaScript Objects with Examples

In this tutorial, you will learn all about JavaScript objects

JavaScript Objects

In JavaScript object is a collection of properties where each property has a value associate with the key.

Create an object

Use curly brackets {…} to create an object.

See the following:

let empty = {};

To create an object with properties, using the key : value pair.

See the following snippet:

let mobile = {
    name: 'apple',
    model: 's7',
    price: '$ 10000'
};

The mobile object has three properties name, model, and pricewith the corresponding values 'apple', 's7'   and '$10000'.

Accessing objects properties

There are two ways to access the property of an object, see the following: the dot notation and array-like notation.

1) The dot notation (.)

The following syntax shows how to use the dot notation to access a property of an object:

objectName.propertyName

i.e, to access the name property of the mobile object, you use the following expression:

mobile.name

The following snippet creates a mobile object and console name and model of mobile objects:

let mobile = {
    name: 'apple',
    model: 's7',
    price: '$ 10000'
};

console.log(mobile.name);
console.log(mobile.model);

2) Array-like notation ( [])

The following syntax shows how to access the value of an object’s property via the array-like notation:

objectName['propertyName'];

For example:

let mobile = {
    name: 'apple',
    model: 's7',
    price: '$ 10000'
};

console.log(mobile['name']);
console.log(mobile['price']);

Suppose, you have property with contains spaces, you need to place it inside quotes.

See the following:

let homeAddress = {
   'house no': 3960,
    street: 'North 1st street',
    state: 'CA',
    country: 'USA'
};

To access the 'house no', you must use the array-like notation:

homeAddress['house no'];

If you use the dot notation, you will get an error:

homeAddress.'house no';

Error:

SyntaxError: Unexpected string

Reading from a property that does not exist will result in an undefined. For example:

console.log(homeAddress.district);

Output:

undefined

Change the property’s value

To change the value of a property, you use the assignment operator. For example:

let mobile = {
    name: 'apple',
    model: 's7',
    price: '$ 10000'
};

mobile.name = 'Samsung';

console.log(mobile);

Output:

{name: "Samsung", model: "s7", price: "$ 10000"}

Add a new property to an object

The following expression adds the weight property to the mobile object and assigns 150g to it:

let mobile = {
    name: 'apple',
    model: 's7',
    price: '$ 10000'
};

mobile.name = 'Samsung';

mobile.weight= '150g';

console.log(mobile); // {name: "Samsung", model: "s7", price: "$ 10000", weight: "150g"}

Delete a property of an object

Using delete operator, To delete a property from an object:

delete objectName.propertyName;

The following example removes the price property from the mobile object:

delete mobile.price;

Check if a property exists

Using the in operator, You can check if a property exists in an object:

propertyName in objectName

The following example creates an mobile object and uses the in operator to check if the modeland weightproperties exist in the object.

let mobile = {
    name: 'apple',
    model: 's7',
    price: '$ 10000'
};

console.log('model' in mobile);
console.log('weight' in mobile);

Output:

true
false

Iterate over properties of an object using for...in loop

To iterate over all properties of an object without knowing property names, you use the for...in loop, see the following syntax:

for(let key in object) { 
    // ...
};

The following shows, to creates a book object and iterates over its properties using the for...in loop:

let book = {
    title: 'JavaScript',
    tags: ['es6', 'javascript', 'node.js'],
    price: '$100'
};

for (const key in book) {
    console.log(book[key]);
}

Functions

The following syntax shows how to tag function to the book object:

let book = {
    title: 'JavaScript',
    price: '$100'
};

book.tag = function () {
   return ['es6', 'javascript', 'node.js']
}

console.log(book.tag());

Output:

["es6", "javascript", "node.js"]

In this example, we added a function expression to create the function and assigned it to the property tag of the book object.

Then, we call the function via the tag property as tag(). When a function is a property of an object, it is called a method.

In ES6, you can even make it more concise:

let book = {
    title: 'JavaScript',
    price: '$100',
    tag() {
        return ['es6', 'javascript', 'node.js']
    }
};

console.log(book.tag());

The this object properties

Suppose you have an array and you want to concatenate two objects properties inside the function, you can use this  object properties.

Inside the method, the this value references the object that contains the method so you can access an object property using the dot notation:

this.propertyName

The following example uses the this value in the getName() method:

let ps = {
    firstName: 'John',
    lastName: 'Doe',
    getName: function () {
        return this.firstName + ' ' + this.lastName;
    }
};


console.log(ps.getFullName());

Output

John Doe

Conclusion

In this tutorial, you have learned the following:

  • An object is a collection of properties where each property has a value associate with the key. An object property key is a string and value can be any valid value.
  • Use the dot notation ( .) or array-like notation ([]) to access an object property.
  • The delete operator removes a property from an object.
  • The in operator check if a property exists in an object.
  • The for...in iterates over properties of an object.
  • When functions are properties of an object, they are called methods.
  • Use the this inside the method to access the object’s properties.

AuthorAdmin

My name is Devendra Dode. I am a full-stack developer, entrepreneur, and owner of Tutsmake.com. I like writing tutorials and tips that can help other developers. I share tutorials of PHP, Python, Javascript, JQuery, Laravel, Livewire, Codeigniter, Node JS, Express JS, Vue JS, Angular JS, React Js, MySQL, MongoDB, REST APIs, Windows, Xampp, Linux, Ubuntu, Amazon AWS, Composer, SEO, WordPress, SSL and Bootstrap from a starting stage. As well as demo example.

Leave a Reply

Your email address will not be published. Required fields are marked *