Objects are an essential building block for data manipulation in JavaScript, the language that runs the internet. Developers may easily organize and arrange data by using JavaScript objects, which are versatile containers. Together, we will unravel objects and examine many essential techniques that simplify our interactions with them.
Understanding Objects in JavaScript
An object in JavaScript is a set of key-value pairs, where the keys are strings, and the values are valid JavaScript data types. These objects combine related characteristics and functions into a single entity, starting with the creation of a simple object via an object literal.
The way to create an object in JavaScript is by using curly braces {}.
Here’s a simple example:
//JavaScript const object = {}; console.log(object); console.log("The type of object is: " + typeof object);
Output:
An example of an object containing key and value pairs:
//JavaScript const person ={ name:'Sarah Maas', age: 37, profession: 'Author' } console.log(person);
Output:
In this example, the keys are name, age, and profession, and the values are ‘Sarah Maas’, ’37’, and ‘Author’, respectively.
How to Access an Object
The two notations used in JavaScript to access an object’s methods and properties are dot notation and bracket notation.
Dot Notation:
Syntax:
object.property
Example:
//JavaScript const person = { name:'Sarah Maas', age: 37, profession: 'Author' } console.log(person.name); console.log(person.age);
Output:
Bracket Notation:
Syntax:
object['property'] or object[expression]
Example:
//JavaScript const person = { name: 'Sarah Maas', age: 37, profession: 'Author', }; const propertyName = 'name'; console.log(person[propertyName]); console.log(person["age"]);
Output:
Dot notation is the easier and more popular method of accessing properties. When the name of the property you wish to access is known to you and is a valid identifier, you use it.
Dot notation is insufficient for multi-word properties, causing errors. To access objects using dot notation, follow the usual rules for declaring a variable, as multi-word string property names are not supported.
//JavaScript // Using camelCase const myObject = { userName: "Percy Jacson" }; console.log(myObject.userName); // Using snake_case const anotherObject = { user_name: "Harry Potter" }; console.log(anotherObject.user_name); // Using square bracket notation const yetAnotherObject = { "user name": "Bob Smith" }; console.log(yetAnotherObject["user name"]);
Output:
Using dot notation for multiword without following the usual rules of declaring a variable it will throw an error.
//JavaScript const objectWithMultiwords ={user name: "Lucas Martin"}; console.log(objectWithMultiwords.user name);
Output:
What an Object Contains
In JavaScript objects, you can have variables, known as properties, and functions, called methods. Properties store data, and methods use the stored data to perform actions within the object.
- Properties: These are variables that are part of an object. The dot notation (object.property) or the bracket notation (object[‘property’]) are used to access properties.
//JavaScript const myObject1 = { name: 'Lily', age: 30, city: 'New York' }; console.log(myObject1.name); // Accessing property using dot notation console.log(myObject1['age']); // Accessing property using bracket notation
- Methods: These are functions that are associated with an object. They can perform actions using the object’s properties. Methods are called using the dot notation (method())
Syntax:
const objectName = { property1: value1, property2: value2, methodName: function() { // method code } };
Example:
//JavaScript const myObject2 = { userName: 'Lily', age: 30, city : 'New York', access: true, showDetails(){ console.log( this.access ? `My name is ${this.userName} and I live in ${this.city} city` : "You don't have") } }; myObject2.showDetails() // calling the method
In the example above, showDetails is a method of the myObject2 object. It uses the userName and city properties to perform an action (logging a message to the console).
Output:
Object Method with Parameters example:
//JavaScript const calculator = { add: function(a, b) { return a + b; }, subtract: function(a, b) { return a - b; } }; console.log(calculator.add(5, 3)); // Output: 8 console.log(calculator.subtract(10, 4)); // Output: 6
Output:
Why Do We Use This Keyword in Objects?
To refer to the current object in a method or function, use the ‘this’ keyword in JavaScript. Depending on how a function is called, the value of the ‘this’ keyword changes. It is a way for a function to reference the object it belongs to or is invoked on.
Let’s go through an example to illustrate the use of this in an object:
//JavaScript const car = { brand: 'Toyota', model: 'Camry', year: 2022, displayInfo: function() { console.log(`This ${this.brand} ${this.model} was manufactured in ${this.year}.`); } }; // Calling the method using the object car.displayInfo();
In this example, displayInfo is a method of the car object. Inside the displayInfo method, this refers to the car object itself. So when we call the car.displayInfo(), it prints:
Output:
If we didn’t use this and directly referenced the properties without it, the code would look like this:
Example:
//JavaScript const carWithoutThis = { brand: 'Toyota', model: 'Camry', year: 2022, displayInfo: function() { console.log('Without using "This" Keyword : This ' + carWithoutThis.brand + ' ' + carWithoutThis.model + ' was manufactured in ' + carWithoutThis.year + '.'); } }; // Calling the method using the object carWithoutThis.displayInfo();
Output:
However, using this makes the code more flexible. If you later decide to change the object’s name from carWithoutThis to something else, you won’t need to update every reference to the object’s properties inside the method.
This is a reference to the current object, determined by function calls, and is useful in object methods for accessing and manipulating its properties.
This keyword with the Arrow Function Object Method:
Arrow functions do not have their own context, so using this inside an arrow function within an object might lead to unexpected behavior.
Example:
//JavaScript const car = { brand: 'Toyota', model: 'Camry', year: 2022, displayInfo : () => { console.log(`This ${this.brand} ${this.model} was manufactured in ${this.year}.`); } }; car.displayInfo();
Output:
Conclusion
JavaScript objects act like handy organizers, simplifying the process of storing and finding information in your code. Explore the next part of our blog, “The Power of Objects in JavaScript You Didn’t Know Part 2,” where we reveal secrets about these helpful methods and share cool tips in my profile. Whether you’re a beginner or eager to learn advanced tricks, this blog is your go-to guide for effortlessly becoming a JavaScript pro. Take the plunge, uncover the world of JavaScript objects, and enhance your coding with organization and power!