Objects in JavaScripts

Objects in JavaScripts

There are 7 data types in JavaScript namely :-

  • number -string
  • null
  • undefined
  • boolean
  • object
  • symbol

We will be looking at object data type, declaration, properties and various operation that can be performed on objects. There is a popular quote in the JS community which says

Almost Everything is an Object

But first what is an Object?

Objects are used to store collection of various data where the value of each data is accessed via a key. sounds cool right ๐Ÿ˜Ž ? let's dig further.

Objects can neither be created nor ๐Ÿ™„ ...

so how do we created an object? we simply create an object as shown below

const club = new Object(); //using the object constructor
const club= {} //using the object literal syntax

Populate object with data

we populate the object by adding a key and creating a value. the value can be of data types such as numbers, strings, arrays or even object yeah i said it objects. take for example the code below, we created a variable club which is an object that holds data about the one of the successful clubs in England ๐Ÿ˜‰

const club = {
name: "Manchester United", 
nickname: "The Red Devils",
founded: 1878,
premierLeague: 20,
coach: {
 name: "Ole Gunner Solskjear",
age: 42,
previousCLubs: ["Molde FK", "Cardiff City"]
  },
rivals: ["Leeds United", "Liverpool", "Manchester City"],
previouslyRelegated: true,
website: "manutd.com"

}

How to access our data

we can access the data in our collection using :

  • dot notation(.)
  • Square bracket notation([ ]) referencing the keys in the object
//using dot notation
console.log(club.name);  // Manchester United

//using square bracket notation
console.log(club["name"]); // Manchester United

Destructuring an Object {extracting data}

Destructuring can simply be defined as method of extracting data from an Object or Array and that data can be assigned to a variable as seen below

// using the dot notation, remember?
const club = club.name; // Manchester United
const nickname = club.nickname; // The Red Devils

the above code can even be written in a better way using ES6 destructuring expression

const {club, nickname } = club;

so a little explanation to the above code ... we created two variables enclosed in a curly bracket and made it equal to the object's name !IMPORTANT NOTICE the new variable names (club and nickname) declared must be a key in the Object

lastly,

Delete Object properties

properties of an object can be deleted by using the delete keyword as shown below

delete club.previouslyRelegated; // deletes the key and value

Now you know the basics of Object, You can read up more about Objects in JS via MDN