Using JavaScript to check if an object key exists with an if statement

I am searching for an improved way to write the following if statement:

function addGestureendEvent(el) {
  if (el.addEventListener && !el.eventListenerAdded) {
        el.addEventListener('gestureend', doSomething, false);
           el.eventListenerAdded = true;
         }
    };

Would it be more effective to explicitly check for the property? For example:

if (el.addEventListener && el.hasOwnProperty(‘eventListenerAdded’) {
  …
}

Appreciate any suggestions. Thank you.

Answer №1

Technically, it is recommended to utilize

el.hasOwnProperty("eventListenerAdded")
. However, personally, I tend to skip this step. By using a clear and distinct name like you did here, there should not be any issues. You might even consider adding your own unique prefix, such as _dom_eventListenerAdded, to help guide future developers who may have questions ;)

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 the statement true in JavaScript if either true or true or false?

I have implemented this code snippet to prevent my page from being iframed: window.onload = function(){ try { if (window.parent && window.parent.location.hostname !== "app.herokuapp.com"){ throw new Error(); } catch (e){ //do something ...

Ways to eliminate the child element(s) from a highlighted text portion

I'm currently struggling to figure out how to manipulate text elements within a span. When a user selects a portion of text in a div, I successfully append a span element. However, if the user selects the same text again, I want to remove the existing ...

Error: EsLint detected that the classname is not a valid Tailwind CSS class

I am encountering an EsLint error indicating that "className is not a TailwindCSS class" after incorporating custom classes like colors into my tailwind.config.js file. Despite this, I am unsure about how to resolve this issue. Shouldn't EsLint recogn ...

How can you make an element appear when clicking and then disappear with a second click?

Having a bit of an issue here. When I click on the menu button "x," it triggers an onclick event that opens/displays an element. All good so far. But now, I want to click the same menu button "x" to close that same element, and that's where I'm s ...

Is it possible to utilize the output of a function to determine the styling of a div element in Vue?

Hi, I'm trying to use the v-bind:style in my div to apply the textposit function with the textpos prop as a parameter. The function should adjust the style of the div based on the value of the parameter. <div class="container" :style=&qu ...

Cease the firing of ion-change until the values have been successfully loaded from storage

My settings page contains multiple ion-toggle's. There's an onChange method to update local storage when toggled. Standard procedure involves checking existing values in storage on page load and mapping them to the toggles using ngModel. <tab ...

Yii2 HTML helper input must be marked as required

This is the form I have generated using the HTML helper: <div class="row"> <div class='form-group col-lg-6 col-sm-6'> <?= HTML::label('Name:','PropertyContactsNew',['class' => 'control-l ...

How to extract text between any HTML tag using regular expressions

I am trying to extract all content between any HTML tags. My current approach is: var result = data.match(/<p>(.*?)<\/p>/g).map(function(val){ // validate } The pattern I have come up with so far is: <[a-z1-9]{1,10}>(.*?)<&bsol ...

Transmit form information using jQuery's ajax JSON functionality

Hello, I am new to PHP/jquery and I have a question. I would like to know how to send JSON data from a form field (such as name, age, etc.) using AJAX in a JSON format. I have searched for relevant information on this but couldn't find anything concre ...

Having trouble with jQuery's document.ready function not firing properly?

I've been struggling with this issue for a few days now and haven't been able to find a resolution. The problem I'm facing is that two JS scripts in my header are not executing the $(document).ready(...). What's strange is that other sc ...

What is the best way to enable a disabled MUI MenuItem within a table that is being mapped, based on a specific item in the

In my table, I have a mapped object of users: {users.map((user,index) => { <TableRow key={index}> ... The final cell in the table contains a button that is linked to an MUI Menu. One of the menu items should be disabled if a specific aspect of ...

The React form's onChange event is lurking just around the corner

I'm encountering some difficulties while creating a form with React, specifically with the password and confirm password fields. My goal is to enable users to input a password and have it instantly verified against the confirm password field to indic ...

Deciphering Timezone Offset to Find its Name

Looking for a way to convert a user's GMT offset timezone stored in Javascript into the corresponding PHP Timezone Name. For example, how can an offset like "300" or "-200" be converted? Appreciate any guidance on this! Thanks! ...

Include a unique identifier in the SVG nodes generated by Graphviz for enhanced manipulation using JavaScript

I am currently utilizing pydotplus for generating graphs and storing them in SVG using graphviz: For example, here's how I add a node (without specifying a node ID attribute): g.add_node(pydotplus.Node(fn_name, st ...

Optimizing Shader Caching in WebGL: Best Practices

I am currently in the process of developing a WebGL application, and I have encountered some challenges with shader storage... In most examples, shaders are directly written in plaintext within the xHTML file itself. However, this approach can lead to clu ...

Getting Node.js to function seamlessly with tree-model-js

Just wanted to say a big thank you for tree-model-js, it's an amazing library! I'm fairly new to Node.js and I've been trying to incorporate the tree-model into my project. Successfully npm'ed everything. As I attempt to integrate Node. ...

Navigating and extracting nested JSON properties using JavaScript (React)

I am currently working with a nested JSON file that is being fetched through an API. The structure of the JSON file looks something like this: { "trees":{ "name":"a", "age":"9", "h ...

Dynamic calculator using JavaScript within jQuery mobile framework

I am a beginner in javascript and I am currently working on creating a mobile app using Jquery Mobile. My goal is to have the user input one value on each page, and then on the final page, display the calculated result after clicking the submit button. I ...

Optimal strategies for designing navigation bars on contemporary websites

Struggling to find a solid answer for this dilemma. I have multiple html pages and a single navigation bar that I want to include on all pages for consistency. The idea of duplicating the html code for the navigation bar goes against everything I've l ...

Issue with Axios code execution following `.then` statement

Recently diving into the world of react/nodejs/express/javascript, I encountered an interesting challenge: My goal is to retrieve a number, increment it by 1, use this new number (newFreshId) to create a new javascript object, and finally add this event t ...