JavaScript  Object Basic?

JavaScript Object Basic?

In this article, we will learn about the basic object.

The object is a set of data collection. the data is anything like a number, string, boolean, bigint, null or undefined. Inside the object, we also write variables and functions and these variables and functions are known inside object properties and methods.

The inside object has two things one is key and second is the key's value and both are called together property.

Creating object:

**object initializer / literal syntax.**

firstly type the variable keyword and then write the object name after the equal sign write curly braces and here our empty object is ready. Using the console we find the output empty object.

const obj = {}//{}

ok, now let's fill the data inside the object.

const obj1 = {
  name: ["bob", "smith"],
  age: 38,
  bio: function () {
    console.log(`${this.name[0]} ${this.name[1]} is ${this.age} years old`);
  },
  introduceSelf: function () {
    console.log(`Hi i'm ${this.name[0]} ${this.name[1]}`);
  },
};
console.log(obj1.name); //[ 'bob', 'smith' ]
console.log(obj1.name[0]); //bob
console.log(obj1.age); //38
console.log(obj1.bio()); //bob smith is 38 years old
console.log(obj1.introduceSelf()); //Hi i'm bob smith

our above object has data and this data is a number, an array and two functions, first two data types we called property inside the object and the second two functions we called method.

when we want to declare a method inside an object we use shorthand property bio(){} instead of writing bio: function(){}.

Dot Notation:

above we use to access the property value by dot notation obj1.name.

name: ["bob", "smith"];
console.log(obj1.name[0]);//bob
console.log(obj1.name[1]);//smith

The object inside the object:

we also write objects inside using objects let's take the example:

  name: {
    firstName: "bob",
    lastName: "smith",
  },

console.log(obj1.name.firstName); //bob
console.log(obj1.name.lastName); //smith

Bracket Notation:

we also use bracket notation to access the property instead of using dot notation.

//////////////// bracket notation //////////////////

const obj1bracket = {
  name: {
    firstName: "bob",
    lastName: "smith",
  },
  age: 32,
};

console.log(obj1bracket["name"]["firstName"]); //bob
console.log(obj1bracket["name"]["lastName"]); //smith
console.log(obj1bracket["age"]);//32
  • Note: In some places, we can not use dot notation to access the property, whereas we use bracket notation. Ex:
const obj1bracketN = {
  name: ["bob", "smith"],
  age: 32,
};

function person(nam) {
  console.log(obj1bracketN[nam]);
}
person("name"); //[ 'bob', 'smith' ]
person("age"); //32

Setting object member:

we set(update) the object member using dot notation or bracket notation. Ex:

/////////// Setting(updating) object member ////////////
const obj1SettingMember = {
  name: ["bob", "smith"],
  age: 32,
};

// by dot notation setting member
const setNameByDot = (obj1SettingMember.name[0] = "Atul Singh");
console.log(setNameByDot); //Atul Singh
console.log(obj1SettingMember.name[0]); //Atul Singh
// set member by bracket notation
const setNameByBracket = (obj1SettingMember["age"] = 55);
console.log(setNameByBracket); //55
console.log(obj1SettingMember.age);//55

What means "this" keyword

We use the "this" keyword above code, what is exactly means of "this" keyword, let's understand. "this" keyword only targets the current parent obj, which means if we declare an object, inside object we can not use our parent object name so we use "this" keyword to tell about this keyword is showing all property inside parent object scope.

When we write many objects and declare the same property name inside every object then we use the "this" keyword because it refers to the current parent object whose tells in which object we want to change. If we do not use the "this" keyword then all same properties got changed because no one says which property will change. "this" is equivalent to the current parent object name. "this" keyword mainly use in the constructor. Ex:

//////////////about this keyword/////////

const person1 = {
  name: "bob",
  introduceSelf() {
    //we can't write object name inside object so we
    //writ this instad of writing person1
    //console.log(`Hi i'm ${person1.name}`);
  // this = person1
    console.log(`Hi i'm ${this.name}`); //Hi i'm bob
  },
};
console.log(person1.introduceSelf());

const person2 = {
  name: "Smith",
  introduceSelf() {
    //we can't write object name inside object so we
    //writ this instad of writing person1
    //console.log(`Hi i'm ${person1.name}`);
   // this = person2
    console.log(`Hi i'm ${this.name}`); //Hi i'm Smith
  },
};
console.log(person2.introduceSelf());

Introducing Constructor

When we want to create many objects then we use a constructor for creating objects. Here we build a normal constructor using a function and inside a function, we create an empty object and then we use property and method. the method will be always when we create an object.

function constructor(nam) {
  const obj = {};
  obj.name = nam;

  obj.constructMethod = function () {
    console.log(`Hi i'm ${this.name}`);
  };
  return obj;
}
/////////// first object/////////////
const atul = constructor("atul");

console.log(atul.name); //atul
console.log(atul.constructMethod()); //Hi i'm atul

/////////// second object/////////////
const mohan = constructor("Mohan Singh");

console.log(mohan.name); //Mohan Singh
console.log(mohan.constructMethod()); //Hi i'm Mohan Singh

This function creates and returns a new object each time we call it. The object will have two members:

  • a property name

  • a method constructMethod ().

Note that constructor() takes a parameter name to set the value of the name property, but the value of the constructMethod () method will be the same for all objects created using this function. This is a very common pattern for creating objects.

  • this works fine but the very long process here involves first creating an empty object, initializing it and returning it. A better way is to use a constructor. A constructor is just a function called using the new keyword. When you call a constructor, it will:

  • create a new object

  • bind this to the new object, so you can refer to this in your constructor code

  • run the code in the constructor

  • return the new object. Constructors, by convention, start with a capital letter and are named for the type of object they create. So we could rewrite our example like this:

///////////second constructor method///////////

function Person(name) {
  this.name = name;
  this.giveIntroSelf = function () {
    console.log(`Hi! I'm ${this.name}.`);
  };
}

To call Person() as a constructor, we use new:

const bob = new Person("Bob");
bob.name;
bob.introduceSelf();

const smith = new Person("Smith");
smith.name;
smith.introduceSelf();

WE will study advance JavaScript in next article. Stay tuned with us.