Javascript Objects
An object is a collection of properties, where each property has a key and a value.
Objects are one of the most important data types in JavaScript and are used extensively in the language.
How to create an object in javascript
There are several ways to create objects in JavaScript, but the most common way is to use object literals. An object literal is a comma-separated list of key-value pairs wrapped in curly braces.
Example:
let person = {
name: "John",
age: 30,
isStudent: false,
};
In this example:
- The
personobject has three properties:name,age, andisStudent. - Each property has a key and a value, separated by a colon.
- The keys are strings, and the values can be any valid JavaScript expression.
Accessing Objects Properties
You can access the properties of an object using dot notation or bracket [] notation:
console.log(person.name); // "John"
console.log(person["age"]); // 30
In this example:
- We access the
nameproperty using dot notation. - In the second statement, we access the
ageproperty using bracket notation.
Both methods are equivalent, but dot notation is more common.
Objects and Methods
Objects can also contain methods, which are functions that are stored as object properties:
let calculator = {
add: function (a, b) {
return a + b;
},
subtract: function (a, b) {
return a - b;
},
};
console.log(calculator.add(2, 3)); // 5
console.log(calculator.subtract(5, 2)); // 3
In this example:
- The
calculatorobject has two methods:addandsubtract. - These methods can be called like any other function, using dot notation.
How to modify Objects
You can modify objects by adding, deleting, or changing their properties. Here are some ways to modify objects:
Adding Properties
You can add new properties to an object by assigning a value to a new key:
let person = {
name: "John",
age: 30,
};
person.isStudent = false;
console.log(person); // { name: "John", age: 30, isStudent: false }
In this example:
- We add a new property
isStudentto thepersonobject by assigning a value offalseto a new key.
Changing Properties
You can change the value of an existing property by assigning a new value to its key:
let person = {
name: "John",
age: 30,
};
person.age = 25;
console.log(person); // { name: "John", age: 25 }
In this example:
- We change the value of the
ageproperty of thepersonobject from30to25.
Deleting Properties
You can delete an existing property from an object using the delete operator:
let person = {
name: "John",
age: 30,
};
delete person.age;
console.log(person); // { name: "John" }
In this example:
- We delete the
ageproperty of thepersonobject using thedeleteoperator. - After the deletion, the
personobject only has anameproperty.
Object Methods
There are also several built-in object methods that can be used to modify objects.
Here are a few examples:
let person = {
name: "John",
age: 30,
};
// Object.keys() method returns an array of the object's keys
console.log(Object.keys(person)); // ["name", "age"]
// Object.assign() method can be used to merge objects
let student = {
major: "Computer Science",
GPA: 3.5,
};
Object.assign(person, student);
console.log(person); // { name: "John", age: 30, major: "Computer Science", GPA: 3.5 }
In this example:
- We use the
Object.keys()method to get an array of the keys of thepersonobject. - We also use the
Object.assign()method to merge thestudentobject into thepersonobject. - This adds the
majorandGPAproperties to thepersonobject.
Modifying objects is an important part of working with JavaScript objects, and it allows you to create complex data structures and implement object-oriented programming paradigms.
The this keyword in Javascript
The keyword this in JavaScript refers to the object that is currently executing a function or method. In other words, this refers to the context in which the code is being executed.
The value of this can change depending on how the function is called. JavaScript offers multiple techniques for invoking a function, and each way affects the value of this.
Here are some common ways to use this:
In a Function
In a function, this refers to the global object:
function myFunction() {
console.log(this);
}
myFunction(); // Window
In this example:
thisrefers to the global object (Windowin a browser environment).
In an Object Method
In an object method, this refers to the object that the method is a property of:
let person = {
name: "Ramesh",
age: 30,
sayName: function () {
console.log(this.name);
},
};
person.sayName(); // "Ramesh"
In this example:
thisrefers to thepersonobject, because thesayNamemethod is a property of the person object.
In an Event Handler
In an event handler, this refers to the element that triggered the event:
<button onclick="console.log(this)">Click me</button>
In this example:
thisrefers to the button element that was clicked.
Using Call or Apply
You can use the call or apply methods to specify the value of this explicitly:
let person = {
name: "Ramesh",
age: 30,
sayName: function () {
console.log(this.name);
},
};
let newPerson = {name: "Suresh", age: 25};
person.sayName.call(newPerson); // "Suresh"
In this example:
- We use the
callmethod to call thesayNamemethod of thepersonobject with a different value ofthis. - The value of
thisis set to thenewPersonobject, so the output is"Suresh".