Series: JavaScript 101
- About JavaScript 101
- Hello World in Web Browser
- Hello World in Node.js
- Variable in JavaScript
- Data Types in JavaScript
- Array in JavaScript
- Object in JavaScript
- Spread Operator in JavaScript
- Loops in JavaScript
- Conditional Statements in JavaScript
- Functions in JavaScript
- Object-Oriented Programming in JavaScript
Objects are an essential part of JavaScript programming, they allow you to store and manipulate data in a more organized manner. Understanding objects and how to work with them is crucial for any JavaScript developer. In this article, we will be breaking down the concept of objects, starting with the basics of declaring and accessing properties, and then diving into the various ways to manipulate them. We'll use simple analogies and code examples to make the concepts easy to understand for beginners. Get ready to unlock the power of objects in JavaScript!
Create an object
To start, think of objects as little containers or boxes that hold information. Each box has a unique label or "key" that you can use to access its information or "value".
Another analogy to keep in mind is that objects are similar to dictionaries. Just like a dictionary, objects have a collection of key-value pairs, where each key is like a word and its value is like the definition.
In JavaScript, you can declare an object using curly braces {}
and separate key-value pairs with a colon :
.
const person = {
name: "John Doe",
age: 30,
occupation: "Developer"
};
Access properties
Accessing the values of an object is just like looking inside the box and finding what's inside. To access a property, you can use dot notation objectName.propertyName
or bracket notation objectName["propertyName"]
.
console.log(person.name); // "John Doe"
console.log(person["age"]); // 30
Add new properties
Manipulating the values of an object is like putting something new in the box or changing what's already there. You can add new properties or change existing ones by simply reassigning values.
person.age = 31;
person.hobbies = ["reading", "travelling"];
console.log(person);
// Output:
// {
// name: 'John Doe',
// age: 31,
// occupation: 'Developer',
// hobbies: [ 'reading', 'travelling' ]
// }
Conclusion
Objects are a powerful data structure in JavaScript, providing a way to store and manipulate data in a structured and organized way. Whether you're a beginner or an experienced developer, understanding and using objects is a crucial part of writing effective and efficient code.