JavaScript Objects
JavaScript object is a non-primitive data-type that allows to store
multiple collections of data.
Note: No need to create classes in order to create objects in javascript.
const student = {
firstName: 'ram',
class: 10
};
Here, student is an object that stores values such as strings and
numbers.
JavaScript Object Declaration
const object_name = {
key1: value1,
key2: value2
}
Here, an object object_name is defined. Each member of an object is
a key: value pair separated by commas and enclosed in curly braces {}.
Object can be defined in a single line.
const person = { name: 'John', age: 20 };
JavaScript Object Properties
In JavaScript, "key: value" pairs are called properties. For example,
let person = {
name: 'John',
age: 20
};
Here, name: 'John' and age: 20 are properties.
Accessing Object Properties
* The value of a property can be accessed by using its key.
1. Using dot Notation
[Link]
const person = {
name: 'John',
age: 20,
};
// accessing property
[Link]([Link]); // John
2. Using bracket Notation
objectName["propertyName"]
const person = {
name: 'John',
age: 20,
};
// accessing property
[Link](person["name"]); // John
JavaScript Nested Objects
An object can also contain another object. For example,
const student = {
name: 'John',
age: 20,
marks: {
science: 70,
math: 75
}
}
// accessing property of student object
[Link]([Link]); // {science: 70, math: 75}
// accessing property of marks object
[Link]([Link]); // 70
In the above example, an object student contains an object value in
the marks property.
JavaScript Object Methods
In JavaScript, an object can also contain a function. For example,
const person = {
name: 'Sam',
age: 30,
// using function as a value
greet: function() { [Link]('hello') }
}
[Link](); // hello
Here, a function is used as a value for the greet key. Use
[Link]() instead of [Link] to call the function inside the
object.