JavaScript Objects

Level : Intermediate
Mentor: Shailendra Chauhan
Duration : 00:01:45

Objects:

Objects in JavaScript are data structures that store key-value pairs and represent entities with properties and methods.

Example:

let car = { brand: "Toyota", model: "Camry" };

Dot Notation for Accessing Object Properties:

You can use dot notation to access properties of an object by directly referencing the property name after the object.

Example:

let person = { name: "Alice", age: 25 };
console.log(person.name);  // Output: Alice

Properties and Values of a JavaScript Object:

You can retrieve all properties or values of an object using 'Object.keys()' or 'Object.values()' respectively.

Example:

let person = { name: "Eve", age: 28 };
let keys = Object.keys(person);     // ['name', 'age']
let values = Object.values(person); // ['Eve', 28]

JavaScript Objects are Mutable:

Objects are mutable, meaning you can modify their properties after creation.

Example:

let dog = { breed: "Labrador" };
dog.breed = "Golden Retriever"; // Mutable

JavaScript Passing Objects as Arguments:

Objects can be passed as arguments to functions, allowing you to modify their properties.

Example:

function incrementAge(person) {
  person.age += 1;
}
let person = { name: "David", age: 40 };
incrementAge(person);  // 'person' age becomes 41

JavaScript Object Methods:

Objects can contain methods (functions) as properties.

Example:

let calculator = {
  add: function(a, b) {
    return a + b;
  }
};
console.log(calculator.add(3, 5));  // Output: 8

JavaScript Destructuring Assignment Shorthand Syntax:

Destructuring allows you to extract object properties into variables.

Example:

let person = { name: "Frank", age: 28 };
let { name, age } = person;  // Destructuring

Shorthand Property Name Syntax for Object Creation:

When creating objects, you can use shorthand notation if the variable names match the property names.

Example:

let name = "Grace", age = 30;
let person = { name, age };  // Shorthand notation

The "this" Keyword:

In a method of an object, 'this' refers to the object itself.

Example:

let car = {
  brand: "Tesla",
  info: function() {
    return 'Brand: ${this.brand}';
  }
};
console.log(car.info());  // Output: Brand: Tesla

JavaScript Function "this":

The value of 'this' in a regular function depends on how the function is called.

Example:

function greet() {
  console.log('Hello, ${this.name}');
}
let person = { name: "Helen" };
greet.call(person);  // Output: Hello, Helen

Self-paced Membership
  • 22+ Video Courses
  • 800+ Hands-On Labs
  • 400+ Quick Notes
  • 55+ Skill Tests
  • 45+ Interview Q&A Courses
  • 10+ Real-world Projects
  • Career Coaching Sessions
  • Email Support
Upto 60% OFF
Know More
Still have some questions? Let's discuss.
CONTACT US
Accept cookies & close this