DEV Community

Neeraj Jain
Neeraj Jain

Posted on

All About JavaScript Objects

Hello learners and reckoners....
It's my first article in such a colossal developer community like [https://dev.to] ....will try my best that my content benefits the readers.

I am assuming that a beginner reading this article must be familiar with (OOP)Object Oriented Programming paradigm. Also, the most important prerequisite of this article is adequate knowledge of Basic JavaScript.

Introduction

The main motive of OOP is to manifest real world entities in the form of code. Each entity has some properties and values associated with it. JS(JavaScript) being an object oriented language makes use of objects to represent these entities. Real world entities have properties and values associated with it and JS has the ability to represent any entity as a JS Object.
One thing to note is that JS is an almost 100% Object Oriented Language since everything in JS is an Object be it Booleans, Strings, Numbers, Arrays etc.

Create Objects

const player = {
   first_name:'Lionel',
   last_name: 'Messi',
   jersey_number:'30',
   age: 33,
   club: 'PSG',
   goals: 635
}

Enter fullscreen mode Exit fullscreen mode

This called an Object Literal.
It is the simplest and the most appropriate way through which objects can be created in JS. Observe that data is stored in Key:Value pairs which makes it very much comprehensive.
We can also create objects using classes in JS just like in any other OOP language like Java, Python, C++ but JS makes this look cool and simple using this approach.
Go to the console and check the type of player by
console.log(typeof(player))
it will give the output as Object.

Another way to create object is as follows:

const player = new Object()
player.first_name:'Lionel',
player.last_name: 'Messi',
player.jersey_number:'30',
player.age: 33,
player.club: 'PSG',
player.goals: 635

Enter fullscreen mode Exit fullscreen mode

Accessing Object Attributes and Values

There are two ways through which we can access values associated with properties

1.Using []

console.log(player[first_name])      //Returns Lionel
console.log(player[last_name])       //Returns Messi
console.log(player[jersey_number])   //Returns 30
console.log(player[age])             //Returns 33
...

Enter fullscreen mode Exit fullscreen mode

Within the square brackets we can not only write direct attributes but also a valid expression....for example let's add another variable in this snippet

const player = {
   first_name:'Lionel',
   last_name: 'Messi',
   jersey_number:'30',
   age: 33,
   club: 'PSG',
   goals: 635
}

const nameKey = 'name'                  //Another Variable//  

console.log(player[first+'_'+nameKey])      //Returns Lionel
console.log(player[last+'_'+nameKey])       //Returns Messi
console.log(player[jersey_number])   //Returns 30
console.log(player[age])             //Returns 33
...

Enter fullscreen mode Exit fullscreen mode

2.Using . Operator

console.log(player.first_name)      //Returns Lionel
console.log(player.last_name)       //Returns Messi
console.log(player.jersey_number)   //Returns 30
console.log(player.age)             //Returns 33
...

Enter fullscreen mode Exit fullscreen mode

Expressions cannot be used in case of . operator and . operator style of accessing attributes looks much cleaner than [] notation.

Modifying Attributes and Values

We can easily modify any of the attributes of the object using the .operator notation in the following manner

const player = {
   first_name:'Lionel',
   last_name: 'Messi',
   jersey_number:30,
   age: 33,
   club: 'PSG',
   goals: 635
}

player.first_name = 'Cristiano'
player.last_name = 'Ronaldo'
player.jersey_number = 7
...

console.log(player)      //All values of attributes have changed// 

Enter fullscreen mode Exit fullscreen mode

Data Within Data

1.Methods as Attributes

We can use methods as attributes while defining objects.

const mikel = {
    firstName : 'Mikel',
    lastName : 'Arteta',
    birthYear: 1978,
    calcAge : function () {
        return 2021 - this.birthYear
    }
}

console.log(`${mikel.firstName} ${mikel.lastName} is ${mikel.calcAge()} years old`)

//Mikel Arteta is 43 years old//
Enter fullscreen mode Exit fullscreen mode

Here this is a reference variable used to refer to any attribute of the current object i.e. the object itself.

2.Arrays as Values

We can have Arrays as values to a particular attribute within an object.

const mikel = {
    firstName : 'Mikel',
    lastName : 'Arteta',
    birthYear: 1978,
    calcAge : function () {
        return 2021 - this.birthYear
    },
    friends : ['Ole', 'Gerard', 'Klopp', 'Henry']
}

console.log(`${mikel.firstName} ${mikel.lastName} has ${mikel.friends.length} friends. ${mikel.friends[3]} is his best friend`);

//Mikel Arteta has 4 friends. Henry is his best friend//
Enter fullscreen mode Exit fullscreen mode

3.Object Within Object

We can have an object as a value of an attribute within an object.

var obj = {
  prop1: 5,
  obj2: {
    prop1: [3, 6, 3],
    prop2: 74,
    prop3: {
      str: "Hello World"
    }
  }
};
console.log(obj.obj2.prop3.str); 

//Hello World//
Enter fullscreen mode Exit fullscreen mode

Looping over an Object

To access all the attributes of an objects at one go we will use a for..in loop.

const player = {
    first_name:'Lionel',
    last_name: 'Messi',
    jersey_number:30,
    age: 33,
    club: 'PSG',
    goals: 635
}

for (let property in player) {
    console.log(`${property} : ${player[property]}`)
}

/*
  first_name : Lionel
  last_name : Messi
  jersey_number : 30
  age : 33
  club : PSG
  goals : 635
*/

Enter fullscreen mode Exit fullscreen mode

That's all for now....hope you found it useful to some extent and I am looking forward for your suggestions for improving my content and feedback for this post.

Thanks and Keep Learning....!!!!!

Top comments (0)