Objects in javscript

An object in JavaScript is a data type that is composed of a collection of names or keys and values, represented in name:value pairs. The name:value pairs can consist of properties that may contain any data type — including strings, numbers, and Booleans — as well as methods, which are functions contained within an object.

Objects in JavaScript are standalone entities that can be likened to objects in real life. For example, a book might be an object which you would describe by the title, author, number of pages, and genre. Similarly, a car might be an object that you would describe by the color, make, model, and horsepower. JavaScript arrays are also a type of object.


Creating an Object

An object is a JavaScript data type, just as a number or a string is also a data type. As a data type, an object can be contained in a variable.

There are two ways to construct an object in JavaScript:

  • The object literal, which uses curly brackets: {}
  • The object constructor, which uses the new keyword

We can make an empty object example using both methods for demonstration purposes.

First, the object literal.

// Initialize object literal with curly brackets
const objLiteral = {};

The object literal initializes the object with curly brackets.

In this next example, we’ll use the object constructor.

// Initialize object
const Author = {
name: 'Dinesh',
age: 12,
hobbey: coding,
greet: function() {
return `hello ${this.name},Are you a coder ?`
}
}

Our new object is Author, which has three properties. Each property consists of a name:value pair, also known as key:value pair. name is one of the property names, which is linked to the property value "Dinesh", a string. It has one method, with a method name of greet and the method value consisting of the contents of the function.

Within greet, you may notice the this keyword. When using this inside of an object, it refers to the current object, in this case Author.

Sending Author to the console will print out the entire object.

Author;

Accessing Object Properties

There are two ways to access an object’s properties.

  • Dot notation: .
  • Bracket notation: []

Let’s revisit our original example object, Author.

const Author = {
name: 'Dinesh',
age: 12,
hobbey: coding,
greet: function() {
return `hello ${this.name},Are you a coder ?`
}
}

If we want to retrieve the property value of age, we can do so with object dot notation by typing the variable name of the object, followed by a dot (.) and the property or method name.

// Retrieve the value of the weapon property
Author.age;
Output
12

AUTHOR.AGE outputs the property value, which is 12. We can also retrieve the same data with object bracket notation. Similar to how you might index and access a string, the syntax for bracket notation is two square brackets ([]) encasing the property name.

// Retrieve the value of the weapon property
Author["age"]
Output
"12

Both dot notation and bracket notation are used regularly. Dot notation is faster and more readable, but has more limitations. Bracket notation allows access to property names stored in a variable, and must be used if an object’s property contains any sort of special character.

In order to retrieve an object method, you would call it much in the same way you would call a regular function, just attached to the object variable.

Author.greet();
Output
"hi Dinesh Are you a coder ?"

In the example above, we see that the string value for the object method greet() is returned.

We can now move on to modifying object properties through adding name:value pairs or modifying existing ones

Adding and Modifying Object Properties

In order to add a new property to an object, you would assign a new value to a property with the assignment operator (=).

For example, we can add a numerical data type to the gimli object as the new age property. Both the dot and bracket notation can be used to add a new object property.

// Add new age property to gimli
Author.address = 39,villa copestreet;
// Add new age property to gimli
Author["address"] = 39,villa copestreet;

We can access that value just as above, with either the dot notation or the bracket notation.

Author.address
Output
39,villa copestreet

A method can also be added to the object by using the same process.

// Add new fight method to Author
gAuthor.codes = function() {
    return `Author,${this.name} codes in javascript`;
}

Once we have created this new object method, we can call it as we did above.

Author.codes();
Output
Author,dinesh codes in javscript

Using the same method, an object’s property can be modified by assigning a new value to an existing property.

// Update Address 
Author.address = "42,bakerystreet";

At this point, if we call the object, we will see all of our additions and modifications.

Author;
Output
{name:"Dinesh", age : 12, address: "42,bakerystreet", age: 139, greet: ƒ, codes: ƒ}

Through assignment operation, we can modify the properties and methods of a JavaScript object.

Removing Object Properties

In order to remove a property from an object, you will utilize the delete keyword. delete is an operator that removes a property from an object.

In the below example, we will remove the weapon property from gimli using delete.

// Remove age from gimli
delete Author.age;
Output
true

The delete operation evaluates as true if the property was successfully removed, or if it was used on a property that doesn’t exist.

We can test the output of Author to see if it succeeded.

gAuthor;
Output
{name: "Dinesh", address: "42,bakerystreet", , greet: ƒ, fight: ƒ}

In the above output, the age  and its associated value are no longer available, showing that we have successfully deleted the property.

In the next section, we’ll go over ways to iterate through objects in JavaScript.

Looping Through Object Properties

JavaScript has a built-in type of for loop that is specifically meant for iterating over the properties of an object. This is known as the for...in loop.

Here is a simplified version of our main object example, Author

const gimli = {
    name: "Gimli",
    race: "dwarf",
    weapon: "battle axe",
};

We can use for...in to traverse through all the properties of gimli and print them to the console. Using bracket notation, we can retrieve the property value as a variable, in this case key.

// Iterate through properties of gimli
for (let key in gimli) {
  console.log(gimli[key]);
}
Output
Gimli dwarf battle axe

We can also retrieve the property name itself using just the first variabe in the for...in loop. We have used a string method to convert the key values to upper case.

// Get keys and values of gimli properties
for (let key in gimli) {
  console.log(key.toUpperCase() + ':', gimli[key]);
}
Output
NAME: Gimli RACE: dwarf WEAPON: battle axe

The for...in loop is not to be confused with the for...of loop, which is used exclusively on the Array object type. You can learn more about iterating through arrays in the “Understanding Arrays in JavaScript” tutorial.

Another useful enumeration method is the Object.keys() method, which will return an array of the object’s keys.

// Initialize method on gimli object to return property keys
Object.keys(gimli);
Output
["name", "race", "weapon"]

This method allows us to work with the keys or names of an object as an array, so you can leverage all of the methods available to JavaScript arrays.


Accessing Nested Objects in JavaScript

  • JavaScript is amazing, we all know that already. But a few things in JavaScript are really weird and they make us scratch our heads a lot. One of those things is the confrontation with this error when you try to access a nested object,

Cannot read property ‘foo’ of undefined

Most of the times when we’re working with JavaScript, we’ll be dealing with nested objects and often we’ll be needing to access the innermost nested values safely.

Let’s take this nested object as an example.

const user = {
id: 101,
email: 'jack@dev.com',
personalInfo: {
name: 'Jack',
address: {
line1: 'westwish st',
line2: 'washmasher',
city: 'wallas',
state: 'WX'
}
}
}

To access the name of the our user, we’ll write

const name = user.personalInfo.name;
const userCity = user.personalInfo.address.city;

This is easy and straight-forward.

But, for some reason, if our user’s personal info is not available, the object structure will be like this,

const user = {
id: 101,
email: 'jack@dev.com'
}

Now if you try you access the name, you’ll be thrown Cannot read property ‘name’ of undefined.

/* Cannot read property 'name' of undefined */const name = user.personalInfo.name;

This is because we’re trying to access name key from an object that does not exist.

The usual way how most devs deal with this scenario is,

/* undefined error will NOT be thrown as we check for existence before access */const name = user && user.personalInfo ? 
user.personalInfo.name : null;

Property Types and Property Access:Property accessors provide access to an object's properties by using the dot notation or the bracket notation.const person1 = {};  // initailize a empty objects literalperson1['firstname'] = 'Mario';person1['lastname'] = 'Rossi';
console.log(person1.firstname);// expected output: "Mario"
const person2 = {  firstname: 'John',  lastname: 'Doe'};
console.log(person2['lastname']);// expected output: "Doe"

Implications:let person = {first Name : 'Nabin',age : 30;hobbies : ['sports','cooking']}console.log(person.first Name) // this is error because we cannot acess property this way .Eg: 2let person = {first-Name : 'Nabin',age : 30,hobbies : ['sports','cooking']}console.log(person.first-Name); // error
Solution to this error
let person = {'first Name' :'Nabin',age : 30,hobbies : ['sports','cooking']}person['first Name'] // 'Nabin'
Javascript ordering object concepts:const number = {5:'hi',1:'here'}console.log(number);Output :{1:'here',5:''hi'}

Comments

Popular posts from this blog

JavaScript — Double Equals vs. Triple Equals - weird things on JavaScript

06_Understanding Execution Context and Execution Stack in Javascript

Creating and inserting element- part-2