Navigating through an object using both dot and bracket notation

Can anyone shed some light on why I keep getting an 'undefined' message when trying to access object properties using dot notation like return contacts[i].prop;?

However, if I use bracket notation like return contacts[i][prop];, it works fine and returns the property of the object.

By the way, this code snippet is from one of the lessons at freecodecamp.org

Below is the code sample :

var info = [
    {
        "name": "John",
        "age": 30,
        "city": "New York"
    },
    {
        "name": "Alice",
        "age": 25,
        "city": "Los Angeles"
    }
];

function displayInfo(name, property){
    for (var i = 0; i < info.length; i++){
        if (info[i].name === name ){
            if (info[i].hasOwnProperty(property)){
                return info[i].property; // This will return the property value
            }
            else{
                return "Property not found";
            }
        }
    }
    return "Name not found";
}

console.log(displayInfo("John", "age"));
console.log(displayInfo("Alice", "city"));
console.log(displayInfo("Bob", "age"));

Answer №1

.property and [property] have distinct meanings.

.property will access the property named "property" directly, for example:

const obj = {
    property: 1,
    value: 2
};

console.log(obj.property);

This code will output 1. On the other hand, [property] will access the property whose name is stored in a variable called property, like this:

const obj = {
    property: 1,
    value: 2
};

const prop = "value";
console.log(obj[prop]);

This will print out 2.

Further information can be found in the documentation on Property Accessors.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is your sticky sidebar getting in the way of your footer?

I've developed a custom sticky sidebar for displaying ads, but I'm facing an issue. When I scroll to the bottom of the page, it overlaps with the footer. Can someone please take a look at this? - var stickySidebar = $('.sticky'); if ...

Unlocking the potential of input values in Angular.jsDiscovering the secret to

I'm currently experimenting with the angular date picker directive. My goal is to retrieve the entered date value from the date picker and log it to the console. However, all of my attempts so far have been unsuccessful. Here's a snippet of my c ...

Slide the next section over the current section using full-page JavaScript

I'm currently developing a website utilizing the FullPage.JS script found at this link . My goal is to have the next section slide over the previous one, similar to what is demonstrated in this example. I've attempted setting the position to fix ...

Refresh the component data according to the vuex state

In order to streamline my workflow, I am developing a single admin panel that will be used for managing multiple web shops. To ensure that I can keep track of which website I am currently working on, I have implemented a website object in my vuex state. Th ...

JavaScript makes it easy to streamline conditions

Can someone help me simplify this repetitive condition? if (this.get('fileUrl')) { const isUnsplash = this.get('fileContainer.asset_kind') === 'UnsplashAsset'; return Asset.create({ url: this.get('f ...

Use a dropdown menu to update the selected value

Issue with displaying drop down values in the second list, despite trying various solutions. When a user selects a country, the corresponding state should be populated from the database into the second drop-down. Any assistance would be greatly appreciated ...

Using Elasticsearch's bulk feature to set unique identifiers(_id) for documents

Whenever I attempt to insert documents into elasticsearch with a set _id, I encounter the following error: The field [_id] is considered a metadata field and cannot be included within a document. It should be utilized in the index API request parameters in ...

Setting null for HttpParams during the call

I am encountering an issue with HttpParams and HttpHeaders after upgrading my project from Angular 7 to Angular 8. The problem arises when I make a call to the API, as the parameters are not being added. Any assistance in resolving this matter would be gre ...

How to set the element in the render method in Backbone?

Currently, I am in the process of developing a web page utilizing BackboneJS. The structure of the HTML page consists of two divs acting as columns where each item is supposed to be displayed in either the first or second column. However, I am facing an is ...

Error: Unable to locate module: Unable to resolve './Page.module.css' in Next.js version 13

When I run npm run build on Vercel and Heroku, I encounter an error that does not occur on my local computer: The error message is Module not found: Can't resolve './Page.module.css' I am trying to import this file from app/page.tsx, and b ...

What is the best way to encapsulate a function that uses `this.item.findElement()` from Selenium in a separate file?

I'm currently working on setting up a Selenium Webdriver and Cucumber.js test environment using Node.js. In the homePageSteps.js file, I have a check to verify if a banner exists on a page: Then('there should be a banner', async function() ...

What is the inner workings behind server side rendering in Next.js?

I am seeking clarification on Server Side Rendering, specifically with Next.js. During server side rendering, I want to confirm the 'execution path' as follows: Client makes a request to the server for the webpage, which serves up an HTML only ...

What is the most efficient way to add an attribute in jQuery - using the attr() method, passing attributes as a key-value object, or directly?

There are three ways that I am aware of for adding a href attribute with a relative link in jQuery: using (1) .attr(), (2) attributes as key-value pair in an argument, or (3) direct writing (if you know other methods, please share in your response so I can ...

The issue with AngularJS multiple $http requests failing to fetch accurate data

I'm having issues with my AngularJS controller and service modules. I want to refresh custController.allCustomers after adding a new customer so that the UI displays the new data. However, when I call custController.createCustomer, the new customer do ...

When trying to gather multiple parameters using @Param in a NestJS controller, the retrieved values turn out

Can someone help me understand why I am struggling to retrieve parameters using the @Param() decorators in my NestJS controller? These decorators are defined in both the @Controller() decorator argument and the @Get() argument. I am relatively new to Nest ...

Encountering a JSON_PARSER_ERROR when trying to call Google FCM using MobileFirstAdapter JS

I am working on integrating Google FCM Api for sending Push Notifications. Below is the snippet of code from my JavaScript file: function sendNotificationToUser() { var request={ path :'/fcm/send', method: 'POST&ap ...

What could be causing the issue with my validation for alphabetical input?

I am currently working on a registration form that only accepts alphabetical input. However, I am facing an issue where my error message appears regardless of whether I input an alphabetical or special character. According to my understanding, the code sho ...

The Angular controller failed to return a defined value

I recently took over a legacy VB.Net application and noticed that both the ng-app and ng-controller directives are present on the HTML element in the root master page: <html runat="server" id="html" ng-controller="MasterController"> The ng-app attr ...

Optimizing the performance of "document.createElement"

When attempting to display multiple rows of data in a popup using a for loop, I initially utilized text strings to create and append the div elements. However, I discovered that using document.createElement resulted in a 20% improvement in performance. D ...

Continue to run upon clicking the button in the Document Object Model

I want the code to constantly change instead of executing only once. By default, the button has a dark mode for text and the background color is pink. When you click the button, the background color changes to black and the text in the button turns into li ...