feat(curriculum): Add interactive examples to What Is an Object in JavaScript, and How Can You Access Properties from an Object (#63300)

Co-authored-by: Ilenia <26656284+ilenia-magoni@users.noreply.github.com>
This commit is contained in:
Clarence Bakosi
2025-10-30 11:54:04 +01:00
committed by GitHub
parent 5d67399cad
commit b9419f4e7c

View File

@@ -5,7 +5,7 @@ challengeType: 19
dashedName: what-is-an-object-in-javascript-and-how-can-you-access-properties-from-an-object
---
# --description--
# --interactive--
In JavaScript, an object is a fundamental data structure that allows you to store and organize related data and functionality.
@@ -43,6 +43,8 @@ objectName.propertyName
Here's how you would use dot notation with our `person` object:
:::interactive_editor
```js
const person = {
name: "Alice",
@@ -54,10 +56,14 @@ console.log(person.name); // Alice
console.log(person.age); // 30
```
:::
Dot notation is concise and easy to read, making it the preferred choice when you know the exact name of the property you want to access and that name is a valid JavaScript identifier (meaning it doesn't start with a number and doesn't contain special characters or spaces).
Bracket notation, on the other hand, allows you to access object properties using a string inside square brackets. Here's how you would use bracket notation:
:::interactive_editor
```js
const person = {
name: "Alice",
@@ -69,8 +75,12 @@ console.log(person["name"]); // Alice
console.log(person["age"]); // 30
```
:::
Bracket notation is more flexible than dot notation because it allows you to use property names that aren't valid JavaScript identifiers. For example, if you had a property name with spaces or that starts with a number, you'd need to use bracket notation:
:::interactive_editor
```js
const oddObject = {
"1stProperty": "Hello",
@@ -81,8 +91,12 @@ console.log(oddObject["1stProperty"]); // Hello
console.log(oddObject["property with spaces"]); // World
```
:::
Another advantage of bracket notation is that it allows you to use variables to access properties dynamically:
:::interactive_editor
```js
const person = {
name: "Alice",
@@ -94,6 +108,8 @@ let propertyName = "city";
console.log(person[propertyName]); // Wonderland
```
:::
This flexibility makes bracket notation particularly useful when you don't know the exact property name at the time you're writing the code, or when you're working with property names that come from user input or some other dynamic source.
It's worth noting that objects in JavaScript are incredibly powerful and versatile. They can contain not just simple values like strings and numbers, but also arrays, or other objects.