Object in JavaScript
In JavaScript, an object in JavaScript is like a storage box that holds various kinds of information. You can store different pieces of data inside an object, and each piece of data is stored in a key-value pair. The key is like the label on the box, and the value is the content inside it.
Syntax:
let objectName = {
property1:value1,
property2:value2,
propertyN:valueN
};
As you can see, property and value are separated by : (colon).
Imagine you want to store details about a person (like their name, age, and city). Instead of keeping all the details separately, you can group them in an object.
Example:
let person = {
name: “Saad”,
age: 25,
city: “London”
};
Explanation:
• name is a property with the value “Saad”.
• age is a property with a value of 25.
• city is a property with the value “London”.
Accessing the Properties of an Object
You can get the information from an object in two ways:
1. Dot Notation:
You can access the properties directly by using a dot (.).
console.log(person.name); // Output: Saad
console.log(person.age); // Output: 25
2. Bracket Notation:
You can also use square brackets ([]) to access properties. This is useful if the property name has spaces or is stored in a variable.
console.log(person[“city”]); // Output: London
Changing or Adding Properties
You can change the value of a property or add new properties to an object.
Change a Property:
person.age = 26; // The person’s age is now 26
console.log(person.age); // Output: 26
Add a New Property:
person.job = “Developer”; // We added a job property
console.log(person.job); // Output: Developer
Now the person’s object looks like this:
let person = {
name: “Saad”,
age: 26,
city: “London”,
job: “Developer”
};
Methods in Objects
A method is like a function that lives inside an object and can perform actions related to that object.
Methods in Objects:
Let’s add a greet method to our person object. This method will return a greeting message that uses the person’s name.
let person = {
name: “Saad”,
age: 26,
city: “London”,
greet: function() {
return “Hello, my name is ” + this.name + “!”;
}
};
console.log(person.greet()); // Output: Hello, my name is Saad!
Here, this.name refers to the name property of the person object. The method greet() combines the name with a greeting message.
Output:
Looping Through an Object
If you don’t know how many properties an object has, you can loop through the object and check each one.
Example of Looping Through an Object:
let person = {
name: “Saad”,
age: 26,
city: “London”
};
for (let key in person) {
console.log(key + “: ” + person[key]);
}
The key is the name of the property, and person[key] gives you the value of that property.
Output:
Displaying an Object as a String
Sometimes, you want to see the whole object as a string. To do this, you can use the JSON.stringify() method & Object.values method etc.
Example of Object.values():
Object.values() is a JavaScript method that returns an array containing all the values of an object’s enumerable properties.
let person = {
name: “Saad”,
age: 26,
city: “London” };
// Using Object.values() to get an array of values
let personValues = Object.values(person);
console.log(personValues); // Output: [“Saad”, 26, “London”]
Explanation:
• Object.values() is a method that extracts just the values from an object.
• For the person object, Object.values(person) returns an array of those values: [“Saad”, 26, “London”].
• This array is stored in the variable personValues and then logged to the console.
Output:
Example of JSON.stringify():
JSON.stringify() is a JavaScript method that converts a JavaScript object or value into a JSON-formatted string.
let person = {
name: “Saad”,
age: 26,
city: “London”
};
let personString = JSON.stringify(person);
console.log(personString); // Output: {“name”:”Saad”,”age”:26,”city”:”London”}
Explanation:
• JSON.stringify() takes a JavaScript object (person in this case) and converts it into a JSON string.
• The result is a string representation of the object, which can be useful for saving, sending, or storing data in a standardized format (JSON).
Output:
Course Video
An object in JavaScript is a collection of key-value pairs where the keys are strings (or symbols) and the values can be any type, such as strings, numbers, or functions. Learn more in our JavaScript object free course video.
You can create objects using:
- Object Literals:
let person = { name: “John”, age: 30 };
- new Object() Constructor:
let person = new Object();
person.name = “John”;
person.age = 30;
- Properties: Values associated with a key in an object.
- Methods: Functions stored as properties in an object.
Explore this concept in the Free JavaScript object tutorial for beginners.
You can access properties using:
- Dot Notation: object.property
- Bracket Notation: object[“property”]
Example:
console.log(person.name); // Dot notation
console.log(person[“age”]); // Bracket notation
Learn more in our JS object with free tutorial.
The this keyword refers to the current object in the context of a method.
Example:
let person = {
name: “John”,
greet: function() {
console.log(`Hello, my name is ${this.name}`);
}
};
Check out practical uses in the JavaScript object free course video.
Yes, you can add or delete properties at runtime.
Example:
person.gender = “male”; // Adding
delete person.age; // Deleting
Discover how in the Learn JS object with free video tutorial.
- keys(): Returns an array of all the keys in an object.
- values(): Returns an array of all the values in an object.
Learn this step-by-step in the Free JavaScript object tutorial for beginners.
- Shallow Cloning: Copies only the first level of an object.
Example: Object.assign() or spread operator (…). - Deep Cloning: Creates a complete copy of the object, including nested objects.
Example:
let deepClone = JSON.parse(JSON.stringify(object));
Find detailed explanations in the JS object with free tutorial.
Use the in operator or hasOwnProperty().
Example:
console.log(“name” in person); // true
console.log(person.hasOwnProperty(“age”)); // false (if deleted)
Watch practical demonstrations in the JavaScript object free course video.
- Use consistent naming for properties.
- Avoid modifying objects directly; use immutability techniques where possible.
- Leverage ES6 features like destructuring and object literals.
Learn these tips in the Free JavaScript object tutorial for beginners.