JavaScript Object and it’s method

JavaScript Object and it’s method

JavaScript object is a non-primitive data-type that allows us to store multiple collections of data.

Here is an example of a JavaScript object.

// object
const student = {
    firstName: 'ram',
    class: 10
};

Here, student is an object that stores values such as strings and numbers.

"This" keyword

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.

JavaScript Methods

JavaScript methods are actions that can be performed on objects.

A JavaScript method is a property containing a function definition.

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:

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Objects</h2>
<p>Creating and using an object method.</p>
<p>A method is actually a function definition stored as a property value.</p>

<p id="demo"></p>

<script>
const person = {
  firstName: "John",
  lastName: "Doe",
  id: 5566,
  fullName: function() {
    return this.firstName + " " + this.lastName;
  }
};

document.getElementById("demo").innerHTML = person.fullName();
</script>
</body>
</html>

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();

console.log(x);
//output: HELLO WORLD!

Thanks for reading this blog!😊