Objects in JavaScript
Basics of Objects
--
Field notes while going through the JavaScript Roadmap
What is an Object?
An Object
in JavaScript is a data type that stores a collection of properties in key-value pairs. Each key-value pair is used to define characteristics of any arbitrary item.
The key of an Object
must be a string, whereas the value can be of any data type (including another object, or function — also known as a method).
Example:
- A pen has several properties such as colour, brand, material, etc.
let pen = {
colour: "black",
brand: "Pilot",
material: "metal"
}
How can we create objects?
There are two ways which we can do this:
- Create an object via the constructor
let user = new Object();
2. Using the object literal syntax
let user = {};
How can we assign a property in an object?
There are two ways we can assign a property to an object:
- Dot syntax
let user = {};
user.age = 25;
2. Square brackets
let user = {};
user["age"] = 25;
How can we extract a property in an object?
There are two ways we can extract a property in an object:
- Dot syntax
let user = {
age: 25,
name: "Jane"
}
console.log(user.name); // Output: "Jane"
2. Square brackets
let user = {
age: 25,
name: "Jane"
}
console.log(user["name"]); // Output: "Jane"
How to delete a property in an object
delete user.age
Check if a key exists in an object
console.log("name" in user);
// Output: true
How to loop through keys / values
To extract the keys:
let user = {
age: 25…