JavaScript Objects

 JavaScript Objects

1. What is a JavaScript Object?

  • JavaScript objects are collections of key-value pairs.

  • Keys (or properties) are strings, while values can be of any data type (numbers, strings, arrays, functions, or even other objects).

  • Objects are used to store structured data.

2. Creating an Object

There are multiple ways to create an object in JavaScript:

(a) Using Object Literal

let student = {

    name: "John Doe",

    age: 20,

    course: "JavaScript",

    isEnrolled: true

};

console.log(student.name); // Output: John Doe

(b) Using the new Object() Constructor

let employee = new Object();

employee.name = "Alice";

employee.salary = 50000;

console.log(employee.salary); // Output: 50000

(c) Using a Constructor Function

function Car(brand, model, year) {

    this.brand = brand;

    this.model = model;

    this.year = year;

}


let myCar = new Car("Toyota", "Corolla", 2022);

console.log(myCar.model); // Output: Corolla

(d) Using Object.create()

let personPrototype = {

    greet: function() {

        console.log(`Hello, my name is ${this.name}`);

    }

};


let person = Object.create(personPrototype);

person.name = "David";

person.greet(); // Output: Hello, my name is David

3. Accessing Object Properties

(a) Using Dot Notation

console.log(student.age); // Output: 20

(b) Using Bracket Notation

console.log(student["course"]); // Output: JavaScript

4. Adding and Modifying Properties

student.email = "john@example.com"; // Adding new property

student.age = 21; // Modifying existing property

console.log(student.email); // Output: john@example.com

5. Deleting Properties

delete student.isEnrolled;

console.log(student.isEnrolled); // Output: undefined

6. Checking if a Property Exists

console.log("age" in student); // Output: true

console.log(student.hasOwnProperty("email")); // Output: true

7. Looping Through an Object

(a) Using for...in

for (let key in student) {

    console.log(`${key}: ${student[key]}`);

}

(b) Using Object.keys()

console.log(Object.keys(student)); // Output: ["name", "age", "course", "email"]

(c) Using Object.values()

console.log(Object.values(student)); // Output: ["John Doe", 21, "JavaScript", "john@example.com"]

(d) Using Object.entries()

console.log(Object.entries(student));

// Output: [["name", "John Doe"], ["age", 21], ["course", "JavaScript"], ["email", "john@example.com"]]

8. Nested Objects

let company = {

    name: "TechCorp",

    location: "New York",

    employees: {

        manager: "Alice",

        developers: ["Bob", "Charlie"]

    }

};


console.log(company.employees.manager); // Output: Alice

console.log(company.employees.developers[0]); // Output: Bob

9. Objects with Methods

Objects can have functions as properties, known as methods.

let user = {

    name: "Michael",

    greet: function() {

        console.log(`Hello, ${this.name}!`);

    }

};


user.greet(); // Output: Hello, Michael!

10. Object Destructuring

let { name, age } = student;

console.log(name, age); // Output: John Doe 21

11. Object Spread and Merge

(a) Using the Spread Operator (...)

let obj1 = { a: 1, b: 2 };

let obj2 = { c: 3, d: 4 };

let mergedObj = { ...obj1, ...obj2 };

console.log(mergedObj); // Output: { a: 1, b: 2, c: 3, d: 4 }

(b) Using Object.assign()

let newObj = Object.assign({}, obj1, obj2);

console.log(newObj); // Output: { a: 1, b: 2, c: 3, d: 4 }

12. JSON (JavaScript Object Notation)

(a) Convert Object to JSON

let jsonString = JSON.stringify(student);

console.log(jsonString); // Output: {"name":"John Doe","age":21,"course":"JavaScript","email":"john@example.com"}

(b) Convert JSON to Object

let jsonObject = JSON.parse(jsonString);

console.log(jsonObject.name); // Output: John Doe


Conclusion

  • JavaScript objects are versatile and essential for handling data.

  • They allow structured storage, manipulation, and retrieval.

  • Objects support nesting, looping, and built-in methods for efficient programming.

Comments

Popular posts from this blog

Events in javascript

Arrays In JS