In this blog post, we will discuss how to retrieve information from an object using JavaScript. We will provide a code snippet that demonstrates how to access the properties of an object and display them on the console.
Code
const example = {
model: '1E78V2',
energyLevel: 100,
provideInfo() {
return `I am ${this.model} and my current energy level is ${this.energyLevel}.`
}
};
console.log(example.provideInfo());
Code Explanation
The provided code snippet showcases a JavaScript object called example
. This object has two properties – model
and energyLevel
, which are set to ‘1E78V2’ and 100 respectively. The object also contains a method called provideInfo()
.
The provideInfo()
method is defined using the ES6 arrow function syntax. When invoked, it returns a string that includes the value of model
and energyLevel
properties of the example
object.
To execute the code and see the result, the console.log()
function is used to output the result of the example.provideInfo()
method.
Here’s the provided code snippet:
javascript
const example = {
model: '1E78V2',
energyLevel: 100,
provideInfo() {
return `I am ${this.model} and my current energy level is ${this.energyLevel}.`;
}
};
console.log(example.provideInfo());
When this code is executed, it will display the following output in the console:
I am 1E78V2 and my current energy level is 100.
By using this code snippet as a reference, you can retrieve information from an object in JavaScript and utilize it as needed in your programs. Feel free to modify the example code and explore different scenarios to enhance your understanding of working with objects in JavaScript.
Remember to practice and experiment as much as possible to solidify your knowledge in this area. Happy coding!
Also checkout the following codes.
How to Iterate through an Object in JavaScript – Program to Print Object Key-Value Pairs
How to Use JavaScript Objects and Methods: Program to Give Details of an Example