Would it be frowned upon in JavaScript to use "if (somestring in {'oneoption':false, 'secondoption':false})"?

Is the use of this construct considered a bad practice in JavaScript and could it lead to unexpected behavior?

if (e.target.name in {name: '', number: ''}) {
  // do something
}

This code checks if the 'name' attribute of an HTML node exists in the keys of the "object" and proceeds if it does. It's a basic check to see if the clicked element is one we need. How does it compare performance-wise to something like this?

if(['name','number'].some(a=>a==e.target.name)) {
  // do something
}

What is the optimal way to perform these checks both in terms of typing and performance?

Answer №1

A potential issue arises when using the in operator because it checks the entire prototype chain, leading to unexpected positives.

"constructor" in {name: '', number: ''} // true  !!

To maintain constant performance, consider using a set. However, for smaller cases, Array#includes is often more readable.

new Set(['name', 'number']).has(e.target.name);
['name', 'number'].includes(e.target.name);

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

How can you efficiently access the 'app' object within a distinct route file?

When using Express 4, the default behavior is to load routes from a separate file like so: app.use('/', routes); This would load routes/index.js. I am working with a third-party library that directly interacts with the app object itself. What& ...

"Learn how to retrieve and assign a value to a select2 dropdown in Vue.js

Currently, I am utilizing vuejs to create and delete dynamic select elements, which is functioning properly. To view the working example, please click here: https://jsfiddle.net/nikleshraut/fgpdp700/2/ var vm = new Vue({ el: "#app", data: { opt ...

Organize database entries by categories for easy navigation

I've developed a web application centered around TV Shows to enhance my understanding of AngularJS. Within my database, I have a table containing various TV shows, each with an assigned category column. For instance, "Dexter" is categorized as "thrill ...

Generate a compressed file from a readable source, insert a new document, and transfer the output

The objective is to obtain an archive from the client, include a file, and transfer it to Cloud Storage without generating a temporary file. Both the client and server utilize the archiver library. The issue with the code snippet provided is that the file ...

Dependency in NPM that imports/includes from the main directory of the application

Imagine creating an application named App, which includes an npm dependency called package. The package requires that the App adheres to a specific file structure: App/ node_modules/ package/ index.js package.json folder/ file.js index.js pac ...

Rapidly update code changes using the development mode in Next.js with the VS Code Remote Container/devcontainer

Struggling to enable Next.js' Fast Refresh feature while using a VS Code Remote Container. Running npm run dev displays the app on localhost, indicating the container functions properly - but Fast Refresh remains ineffective. Next.js version: v11.0.1 ...

Guide to removing a Firebase Storage directory using a Firebase Cloud Function?

I'm having trouble finding the deleteFiles() method and the DeleteFilesOptions argument in the Firebase API reference. My IDE is indicating that this method requires an optional argument, but I can't seem to locate any information on this type. I ...

Unveiling the Power of AngularJS for Parsing JSON Data

A list of images is being generated in a table-like structure using the code snippet below. Each image represents a cell in this table, with its ID specifying its row and column position. <ul> <li class="row"> <ul> & ...

"Enhance your website with interactive jQuery lightbox buttons for easy navigation

As I explore the jquery lightbox plugin, I find it to be quite straightforward. However, I am curious if there is a way to make the "previous" and "next" buttons of the plugin function without the images needing to be named sequentially (e.g., "image1.jpg, ...

Chrome Automatically Playing WebRTC Audio

My webapp has webrtc functionality, but I've noticed a strange issue. When connections are established between Chrome browsers, the audio is not played, while video is. However, this problem doesn't occur with Mozilla users. So... Chrome user 1 ...

Exploring the Power of React's Ref API

Currently, I am following tutorials on Udemy by Max where he discusses how to work with Ref Api's in React 16.3. In one of the lectures, he demonstrated creating a ref inside a container class, not App.js, using this.lastref = React.createRef();. He ...

Issue with retrieving POST body from Ajax call in Play Framework

I am currently attempting to send a POST request to my backend using JSON data. The frontend call appears like this: function register() { var user = $("#form_reg_username").val(); var pass = $("#form_reg_password").val(); var referal = $("#form_reg ...

One issue encountered in the AngularJS library is that the default value does not function properly in the select element when the value and

In this AngularJS example, I have created a sample for the select functionality. It is working fine when I set the default value of the select to "$scope.selectedValue = "SureshRaina";". However, when I set it to "$scope.selectedValue = "Arun";", it does n ...

Creating an easy-to-update catalog utilizing an external file: A step-by-step guide

I am looking to create a product catalog with 1-4 products in a row, each displayed in a box with details and prices. I would like to be able to generate the catalog easily using an XML/CSV file that can be updated. Can anyone provide guidance on how to ac ...

Radio button triggers an ajax call once, but then fails to function

How can I troubleshoot an issue where the ajax function only works once when clicking on a radio button to change its value from 0 to 1, but not back to 0? The form contains a table with radio buttons for each record, and clicking on them triggers the aj ...

The parameter value experiences an abrupt and immediate transformation

I recently created an electron app using Node.js and encountered a peculiar issue that I am unable to resolve: Below is the object that I passed as input: { lessons: [ name: "math", scores: [90, 96, 76], isEmpty: false ] } ...

Why does the UseEffect hook in next.js result in 2 fetch requests instead of the expected 1?

I am encountering an issue where my code is triggering two requests to my API using the GET endpoint. Unfortunately, my understanding of useEffect() is not deep enough to pinpoint where the problem lies. I want to avoid putting unnecessary strain on the ...

Conflicting submissions

Can anyone help me with a JavaScript issue I'm facing? On a "submit" event, my code triggers an AJAX call that runs a Python script. The problem is, if one submit event is already in progress and someone else clicks the submit button, I need the AJAX ...

Utilizing CSS classes based on subelements

I need to assign css classes to items in a list based on certain criteria. Here is an example of the structure I am working with: <ul ng-controller="Navigation"> <li><a href="#">Category A</a> <ul> < ...

Is there a way to change the color of just the most recently clicked anchor element <a>?

I have a sidebar with anchor elements (Link 1,2,3 in my HTML). I want the text color of these anchors to change when clicked. Additionally, I need only one anchor element to be colored at a time, meaning the previous one should return to its normal color. ...