JavaScript object basics

JavaScript object basics

Understand Objects, Properties, and Methods

What are JavaScript Objects and why do we use them?

In JavaScript, an object is like a container that holds different pieces of information or data related to a specific thing. it's a way to group properties (characteristics) and methods (actions) that belong together.

Creating Objects

Simple example-

// Creating an object representing a person
const person = {
    firstName: "John",
    lastName: "Doe",
    age: 30
};

// Accessing properties of the person object
console.log(person.firstName); // Output: John
console.log(person.lastName);  // Output: Doe
console.log(person.age);       // Output: 30

In this code:

  • We use curly braces '{}' to define an object named 'person'.

  • Inside the object, we add properties such as 'firstName', 'lastName', and 'age'.

  • We can access the properties using dot notation (objectName.propertyName) Ex - console.log(person.age); .

This creates a simple person object with first name, last name, and age properties You can add more properties and even methods to perform actions related to person, just like the previous examples. the object allows you to keep related data together and access it easily.

Methods

methods in JavaScript objects are like actions or functions that the object can perform. they allow you to define behaviors associated with the object. Think of methods as the things the object can do.

how to define methods in an object and use them:

const calculator = {
  add:function(a,b){
      return a + b;
} 
  subtract:function(a,b){
     return a - b;

} 
  multiply:function(a,b){
     return a * b;
}

// Using methods of the calculator object
const sum = calculator.add(1, 5);
console.log("sum", sum); //Output: sum 6

const difference = calculator.subtract(10, 4);
console.log("Differnece:", differnece); // Output: 6

const product = calculator.multiply(2, 3);
console.log("Product:", product); //Output 6

}

In this code:

  • We define an object named 'calculator'.

  • Inside the object, we have methods like 'add', 'subtract', and multiply.

  • These methods take parameters (inputs) and perform calculations

  • We call the methods using dot notation ('objectName.methodName(parameters)')

  • The methods return values that we can store in variables or use directly.

Methods allow you to encapsulate actions related to the object and reuse them whenever needed. Just like properties, Methods make your organized and easier to understand.

While you can achieve this similar results with functions, using methods within objects provides a more structured and organized approach, especially when dealing with data and behavior closely tied to a specific object. It helps make your code maintainable and easier to reason about.

Using the this Keyword and Interacting with Objects.

In JavaScript, when you're working with objects, the 'this' keyword helps an object refer to itself. It's like saying "me" or "myself" for the object. This makes it easier for the object to talk about its own properties and methods.

Let's see how this works with an example:

Suppose we have a person object with a property 'name' and a method 'greet()':

var person = {
name:"kohinoor",
greet:function(){
console.log("hello, I'm" + this.name + "!");

  }

};

person.greet(); // Output: Hello, I'm kohinoor

In this code:

  • 'this.name' refers to the 'name' property of the 'person' object.

  • When we call 'person.greet()', 'this inside the 'greet()' method points to the 'person' object.

Using ' this ' helps objects use their own data in methods, even when there are multiple objects of the same type.

Now, let's look at how objects interact with each other:

Imagine we have two person objects and we want them to introduce themselves:

var person1 = {
name: "Vidhayak G",
introduce:function(){
   console.log("Hey, I'm " + this.name + ".");
  }
};
var person2 = {
name: "nachatra",
introduce:function(){
   console.log("Hi, I'm " + this.name + ".");
  }
};

person1.introduce(); // Output: Hey, I'm Vidhayak G
person2.introduce(); // Output: Hi, I'm nachatra

By mastering the this keyword and understanding object interaction, you can create dynamic and flexible code where objects communicate effectively and work together.

Object Manipulation

Object manipulation in JavaScript involves changing or using the properties and methods of an object to achieve specific tasks. It's like giving an object new characteristics or making it perform different actions.

Simple example-

Suppose we have a cat object with a property 'name' and a method 'meow()'

var cat = {
  name:"unchable",
  meow:function(){
   console.log(this.name + " says meow!");

   }
};

Now, we want to manipulate the cat object:

Changing Properties

We can change the 'name" property of the cat object:

cat.name = "Jashu";
cat.meow(); //Output: Jashu says meow!

Here, we updated the 'name' property to "Jashu" and then called the "meow()' method.

Adding New Properties

We can add a new property 'age' to the cat object:

cat.age = 18;
console.log(cat.age) //Output: 18

We assigned a value of 18 to the 'age' property, and now the cat object has a new piece of information.

Built-in Object Methods

JavaScript provides useful methods for object manipulation:

var keys = Object.keys(cat); // Gets an array of property names
console.log(keys); // Output: [ 'name', 'meow', 'age' ]

var values = Object.values(cat); // Gets an array of property values
console.log(values); // Output: [ 'Jashu', [Function: meow], 18 ]

Here, we used Object.keys() to get an array of property names and Object.values() to get an array of property values from the cat object.

Object manipulation allows you to customize and control how objects behave.

JSON (JavaScript Object Notation) -

JSON, short for JavaScript Object Notation, is a way to format and exchange data between computers. It's like a language that both humans and computers can understand easily. JSON is often used to represent complex data in a simple, organized manner.

How JSON works with example:

Suppose we want to represent information about a book using JSON:

{
  "title": "Harry Potter and the Sorcerer's Stone",
  "author": "J.K. Rowling",
  "year": 1997,
  "isBestseller": true
}

In this JSON object:

  • "title", "author", "year", and "isBestseller" are keys.

  • "Harry Potter and the Sorcerer's Stone", "J.K. Rowling", "1997", and "true" are values.

JSON uses curly braces '{}' to define objects. Each key is followed by a colon ':' and its corresponding value. key-value pairs are separated by

Let's see how we can use JSON in JavaScript:

Parsing JSON

To use JSON data in JavaScript, you can parse it to convert it into an object:

var bookJSON = '{"title": "The Hobbit", "author": "J.R.R. Tolkien", "year": 1937}';
var bookObject = JSON.parse(bookJSON);

console.log(bookObject.title); // Output: The Hobbit
console.log(bookObject.author); // Output: J.R.R. Tolkien

Here, we converted the JSON data into a JavaScript object using

'JSON.parse()' and then accessed its properties.

Creating JSON

To create JSON from a JavaScript object, you stringify it:

var newPerson = {
  name: "sohil",
  age: 28,
  isStudent: false
};

var newPersonJSON = JSON.stringify(newPerson);
console.log(newPersonJSON);

The JSON.stringify() function converts the JavaScript object into a JSON-formatted string.

JSON is used extensively for exchanging data between a web server and a web application, making API requests and responses, and storing configuration data. Its simplicity, compatibility with different programming languages, and human readability make it a versatile choice for data interchange.

Thank you for taking the time to read my blog on JavaScript Object, and their essential concepts. I hope you found this information. If you have any questions or thoughts, or if this blog provided you with new knowledge that you'd like to share, please don't hesitate to reach out. Your feedback is greatly appreciated and encourages me to continue. that's informative and helpful. Happy coding and may your journey in programming be both enjoyable and rewarding!