In javascript, objects are one of the fundamental data types and are used to store collections of key-value pairs. They provide a way to represent complex data structures and organize related data.
Here's an example of how to create an object in javascript using object literal notation:
javascript
Const person = {
name: 'john',
age: 30,
profession: 'developer'
};
In this example, we created an object called `person` with three properties: `name`, `age`, and `profession`. The properties are defined as key-value pairs, where the keys are strings (e.g., `'name'`, `'age'`, `'profession'`) and the values can be of any javascript data type (e.g., `'john'`, `30`, `'developer'`).
You can access the properties of an object using dot notation (`objectname.propertyname`) or bracket notation (`objectname['propertyname']`). For example:
javascript
Console.log(person.name); // output: 'john'
Console.log(person['age']); // output: 30
You can also modify or add properties to an object dynamically:
javascript
Person.age = 31; // modifying an existing property
Person['profession'] = 'senior developer'; // modifying an existing property
Person.location = 'new york'; // adding a new property
Console.log(person);
/*
Output:
{
name: 'john',
age: 31,
profession: 'senior developer',
location: 'new york'
}
*/
Objects can also contain nested objects or functions as property values, allowing you to create more complex data structures:
```javascript
Const car = {
make: 'toyota',
model: 'camry',
year: 2020,
owner: {
name: 'alice',
age: 28
},
start: function() {
console.log('the car engine has started.');
}
};
Console.log(car.owner.name); // output: 'alice'
Car.start(); // output: 'the car engine has started.'
```
In this example, the `car` object has a nested `owner` object and a `start` function property.
Javascript objects also have several built-in methods and properties, such as `object.keys()`, `object.values()`, and `object.entries()`, which allow you to work with the properties of an object in various ways. These methods provide ways to iterate over an object's properties, extract keys or values, or convert the object to an array.
These are just the basics of working with objects in javascript. Objects are a versatile and powerful feature of the language and are extensively used in javascript programming.
Silan Software is one of the India's leading provider of offline & online training for Java, Python, AI (Machine Learning, Deep Learning), Data Science, Software Development & many more emerging Technologies.
We provide Academic Training || Industrial Training || Corporate Training || Internship || Java || Python || AI using Python || Data Science etc