In JavaScript, square brackets []
can be used to access properties of an object dynamically. For example, consider the following object:
let obj = {
name: "John",
age: 30
};
You can access the name
property of obj
using dot notation like this:
console.log(obj.name); // Output: "John"
However, if you have a string representation of the property you want to access, you can use square brackets to access the property dynamically:
let prop = "name";
console.log(obj[prop]); // Output: "John"
This can be useful when you want to dynamically access properties based on user input or some other condition. You can also use expressions inside square brackets to dynamically access properties:
let index = 0;
let array = ["John", "Jane", "Jim"];
console.log(array[index]); // Output: "John"
Note that you can use square brackets with both objects and arrays, but the way you access properties is slightly different. With objects, you use strings to access properties, while with arrays, you use integers to access elements.
+ There are no comments
Add yours