Objects In Javascript and its methods

Objects are important data structures in JavaScript. This is partly because arrays are objects in JavaScript, and you'll use them all the time.

What is a JavaScript Object?

Objects let you group related data together and split code into logical pieces. In JavaScript, we have primitive values and reference values. Number, Boolean, Null, Undefined, String, and Symbol are primitive values, while objects like DOM nodes, Arrays, and so on are reference values.

How to Create an Object in JavaScript

const person = {
  name:'kamal',
  age:30,
  friends:[
     'Shola','Ade','Ibraheem'
  ],
  greet:function(){
    alert('Hello World')
  }
}

How to Add Properties in an Object

There are two major approaches to adding properties to an object in JavaScript. The first is to create a brand-new object.

let person = {
  name:'kamal',
  age:30,
  friends:[
     'Shola','Ade','Ibraheem'
  ],
  greet:function(){
    alert('Hello World')
  }
}
 person = {
  name:'kamal',
  age:30,
  friends:[
     'Shola','Ade','Ibraheem'
  ],
  greet:function(){
    alert('Hello World')
  },
  isAdmin:true
}

JavaScript Object Methods

What is this?

In JavaScript, the this keyword refers to an object.

Which object depends on how this is being invoked (used or called).

The this keyword refers to different objects depending on how it is used:

In an object method, this refers to the object.

Alone, this refers to the global object.

In a function, this refers to the global object.

In a function, in strict mode, this is undefined.

In an event, this refers to the element that received the event.

Methods like call(), apply(), and bind() can refer this to any object.

Accessing Object Methods

You access an object method with the following syntax:

objectName.methodName()

You will typically describe fullName() as a method of the person object, and fullName as a property.

The fullName property will execute (as a function) when it is invoked with ().

This example accesses the fullName() method of a person object:

name = person.fullName();

Adding a Method to an Object

Adding a new method to an object is easy:

person.name = function () {
  return this.firstName + " " + this.lastName;
};

Using Built-In Methods

This example uses the toUpperCase() method of the String object, to convert a text to uppercase:

let message = "Hello world!";
let x = message.toUpperCase();

The value of x, after execution of the code above will be:

HELLO WORLD!


Thank you for giving your valuable time, Happy Learning !!