Difference between hasOwnProperty(propName) and hasOwnProperty("propName")

After completing the challenge on Record Collection, I have come up with a functional solution.

I have a question about when to use quotes ("" or '') inside the propName for hasOwnProperty(propName). Can you explain when to use hasOwnProperty(propName) versus hasOwnProperty("propName")?

Below is my solution that works:

function updateRecords(id, prop, value) {
 if (prop != "tracks" && value != "") {
   collection[id][prop] = value;
 }
else if (prop === "tracks" && collection[id].hasOwnProperty("tracks") === false) {
 collection[id].tracks = [];
 collection[id].tracks.push(value);
}

 else if (prop ==="tracks" && value != ""){
   collection[id].tracks.push(value);
 }
else if (value === "") {
   delete collection[id][prop];
 }
  return collection;
}

Interestingly, changing hasOwnProperty("tracks") to hasOwnProperty(tracks) breaks the code. This is perplexing as the example I saw for hasOwnProperty(propName) did not include quotes and failed when quotes were added around propName.

I first learned about hasOwnProperty() from: Testing object for Properties.

Answer №1

It is crucial to utilize a string when checking for the existence of a property on an object. This is especially important when quotes are not used, as it signifies that a variable storing the property name as a string value must be used. This is unrelated to whether the variable shares the same name as the property. For instance, consider the following code snippet where properties are iterated over and checked for ownership within the object (excerpt taken from documentation on Object.prototype.hasOwnProperty):

var buz = {
  fog: 'stack'
};

for (var name in buz) {
  if (buz.hasOwnProperty(name)) {
    console.log('this is fog (' + 
      name + ') for sure. Value: ' + buz[name]);
  }
  else {
    console.log(name);
  }
}

As pointed out by @Gavin, the example demonstrates how the property name can be passed as a string instead of propname

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

Getting a specific element from an Ajax response may involve using JavaScript methods to target the desired

Within my PHP file, there are multiple HTML elements that I am fetching in an AJAX response. Currently, all these HTML elements are being returned in my drop area. How can I adjust the code to only retrieve a specific element, such as an image, like so: P ...

Vue.js - The @oninput.native listener does not trigger in b-form-textarea components

I have a Vue application and I am trying to incorporate Facebook inspired buttons inline in a comment form. Previously, I had a plain JavaScript prototype that was functional. However, when integrating it into my Vue app, I encountered issues due to multip ...

Tips for implementing self-managed state in Vue.js data object

My approach in organizing my Vue application involves using classes to encapsulate data, manage their own state (edited, deleted, etc), and synchronize with the back-end system. However, this method seems to conflict with Vue in some respects. To illustra ...

What is the best way to correct the mouse position in relation to the canvas parent?

I am currently working on incorporating the Vuejs Draw Canvas from this Codepen example into my project as a component. The functionality is all working well, but I've noticed that the mouse position seems to be relative to the window. This causes iss ...

Implementing URL routing and error handling in a Node.js application using the Express framework

As a newcomer to node.js, I appreciate your patience. I've been experimenting with node.js and the express module. I had an idea for handling browser requests and now I have a simple question: Is this approach good practice, or is there a better sol ...

Fill in according to the options selected in the dropdown menu

Recently delving into the world of React, I encountered a design challenge that needs solving. My goal is to have a selection field with various choice values, each offering different sets of KPIs and UOMs. Depending on the chosen value, I should be able t ...

What is the proper way to utilize document.getElementById() within a standalone js file?

As I dive into learning web development for the first time, I've decided to keep my scripts organized in separate files. However, I'm facing a challenge when trying to access elements from these external files. Below is a snippet of the JavaScri ...

Combining a pair of canvases

Currently, I am utilizing a JavaScript library to create a QR Code. This library generates the QR code by displaying it on a canvas. Nevertheless, my goal is to integrate a background behind this QR Code. I attempted to achieve this by first drawing the b ...

Ways to enable automatic scrolling of a page as the content expands (Utilizing collapsible elements)

For a recent project I've been working on, I decided to include 4 collapsible text boxes. However, I encountered an issue where opening content1 would expand and push down content2-4, requiring the user to manually scroll to view the remaining collaps ...

Ways to check for child items in a JSON object

My Angular-built menu uses JSON and spans up to 3 levels deep. Some items have no children, while others go further down the hierarchy. I'm trying to determine if a selected subcategory has child elements in order to hide a button. Each time a subcat ...

Using a dynamic image source in an Ionic 3 background

I am using ngFor to display a list of posts, each of which should have a unique background image. The getBackgroundStyle function is responsible for extracting the URL of the image from the post array. <div class="singlePost" *ngFor="let post of da ...

To enable the radio button upon clicking the list item in JavaScript, simply check the radio button

I am working with radio buttons Here is the HTML code: <input type="radio" class="first" name="bright" checked> <input type="radio" class="second" name="bright" > <input type=" ...

Dependencies in Scala.js for CSS styling

I am currently having an issue implementing Scala.js with the bootstrap library. Including the js file was a simple and straightforward process: jsDependencies +="org.webjars" % "bootstrap" % "3.3.7-1" / "bootstrap.js" minified "bootstrap.min.js" However ...

Having trouble with form validation in React.js? Wondering about the best ways to compare two fields? Let's

It's important to ensure that users enter the same email in both the email and confirmEmail input fields. I've experimented with a few methods, but I'm not certain of the best approach. Is there a simpler way that I might be overlooking? In ...

Utilizing AMAZON_COGNITO_USER_POOLS in conjunction with apollo-client: A comprehensive guide

Struggling to populate my jwtToken with the latest @aws-amplify packages, facing some challenges. Encountering an error when attempting to run a Query: Uncaught (in promise) No current user It seems that when using auth type AMAZON_COGNITO_USER_POOLS, I ...

Can someone help me figure out where I'm going wrong with the JS ternary conditional operator

Looking to improve my JavaScript logic skills as a beginner. Appreciate any tips or feedback on the function and not just this specific question. I'm curious why the code outputs --> [3,5] function divisors(integer) { let divisors = [] for (le ...

Issue with DragControls in Three.js not detecting intersections

My current challenge involves setting up DragControls in my Three.js project. After researching online, I found that the process should be quite simple. The code I have written is as follows: let dragObjects = [obj] const dragControls = new DragControls(dr ...

Is there a way to upload several documents in just one writing?

Can anyone advise me on how to add multiple documents to my Firestore collection using just one write operation? I have over 20,000 records and I'm looking for a cost-effective solution. Is there a way to add multiple docs in a single write? Apprecia ...

Ways to obtain the latitudes and longitudes for various routes between a starting point and a destination

At the moment, I am successfully retrieving all the latitude and longitude coordinates from the source to destination location. However, I am only able to obtain 1 path using this method. Now, I would like to have the ability to choose a specific route p ...

Filter an array using an algorithm inspired by Binary Search Trees

I am facing a challenge with a sorted array of dates, here is an example: let arr = ['2019-03-12', '2019-02-11', '2019-02-09', '2018-06-09', '2018-01-24', ..] The arr has a length of 100,000, and I need t ...