Can you explain how `var in array` differs from using `array.indexOf(var)`?

Currently, I am delving into the world of arrays in JavaScript. My main inquiry revolves around determining the equivalence of the two tests below:

var test = 2;
console.log(test in [1,2,3]);
console.log([1,2,3].indexOf(test) != -1);

Initially, these tests appear to yield similar results. However, after coming across responses on platforms like this and insights from the book I am currently engrossed in, doubts have arisen. It is argued that using the in operator with an array is not supported, but rather intended for objects. This discrepancy prompts the question: why do individuals opt for .indexOf(x), presumed to be linear time, over in, assumed to offer constant time efficiency?

Answer №1

Nope. They are actually quite distinct.

examining in [1,2,3] verifies if there exists a trait known as 2 within the entity. Indeed, it does; possessing the value 3.

[1,2,3].locationOf(examining) retrieves the first characteristic with the numerical representation 2 (situated within the attribute labeled as 1)

suggest that conducting this operation is impossible on an array, solely achievable on an object

It's worthy to note that arrays are essentially type of objects. (A specialized form if we adhere to conventional OO terminology, while not precisely suitable for a prototypal language like JS, but serves its purpose).

The set [1, 2, 3] somewhat resembles an instance of an object { "0": 1, "1": 2, "2": 3 } (still, inheriting several other aspects from the Array constructor).

Answer №2

According to information from MDN website,

The in operator will return true if the specified property exists within the specified object.

in is used to check for keys, similar to using Object.keys(array).indexOf(test)

var a1 = [1,2,3];
var a2 = ['a', 'b', 'c']
var test = 2;

console.log(test in a1)
console.log(test in a2)

// Best practice

//ES5
console.log(a1.indexOf(test)>-1)
console.log(a2.indexOf(test)>-1)

//ES6
console.log(a1.includes(test))
console.log(a2.includes(test))

Answer №3

When checking for an index or if a property of an object exists, the first code snippet does this by:

console.log(test in [1,2,3]);

It is important to note that this code does not check for a specific value within the array like the second code snippet does:

console.log([1,2,3].indexOf(test) != -1);

Answer №4

The in operator determines whether a specified property exists within a given object.

When using the in operator with an array, it checks for the presence of the indices and the length property - as these are the properties specific to arrays:

console.log(Object.getOwnPropertyNames([1, 2, 3]));
console.log(Object.keys([1, 2, 3]));
console.log('length' in [1, 2, 3]);

Object.keys : returns all enumerable properties

Object.getOwnPropertyNames : returns all properties

Answer №5

Give this a shot

let value = 2;
let arrayValue = [1, 5, 2, 4];
let result = arrayValue.indexOf(value);
if(result > -1) {
    console.log("Found it");
} else {
    console.log("Not Found");
}

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

What measures can be taken to avoid RowIDs resetting in jqGrid?

After each pagination action (such as increasing the number of rows or moving to the next page), I noticed that the rowIDs get reset for some reason. For example, let's say I have a total of 75 records. I am displaying 15 records per page, resulting ...

Unable to write or upload error in a Node Express application

My GET and POST APIs are functioning properly, however, my app.put is not working as expected. https://i.sstatic.net/Oc0QT.png Upon sending a PUT request to localhost:3001/contacts/1 using Postman, I am unable to see the console.log output: https://i.ss ...

It is generally not recommended to begin a constructor name with a lowercase letter in jsPDF

I'm attempting to generate a PDF using React const myComponent = () => { const pdfGenerator = () => { const doc = new jsPDF(); //I also attempted: new jsPDF('landscape', 'px', 'a4', 'false'); ...

Running AngularJS controllers should only occur once the initialization process has been fully completed

I am facing a situation where I need to load some essential global data before any controller is triggered in my AngularJS application. This essentially means resolving dependencies on a global level within AngularJS. As an example, let's consider a ...

What are the steps to effectively incorporate Bootstrap into a React project?

I have recently put together a basic webpage with a header and footer. Utilizing Bootstrap for the header components, I have encountered an issue where Bootstrap does not seem to be functioning as expected. Here's a snippet from App.js: import R ...

Utilizing a List<> as a template - asp.net mvc

When I return a view with a List as a model, the code looks like this: List<Indications.Analysis.PrepaymentResult> resultsList = Indications.Analysis.PrepaymentResult.GetPrepaymentResult(indication.Model.Trx, indication.Model.ShockBpsDropList.Value, ...

Issue with UseState causing a re-render not to be triggered

My orders list state works perfectly on the initial update. However, when an order in the database gets updated, the order list is updated but fails to trigger a re-render even with <...> const [orders, setOrders] = useState([]); useEffect(( ...

Tips for transferring data from a file located outside an Angular library to files within the Angular library

In the repository below, you will find a library named posts-lib. This library contains a file named posts.services.ts which is responsible for making http calls and retrieving a list of posts to display on the screen. Additionally, there is a component na ...

Switch between display modes by clicking using collections

I am trying to figure out how to create a function that will only show content for the specific element in which my button is located. Currently, when I click the button it shows content for all elements with the 'one' class, but I want it to dis ...

Preserve the parameter navigation stored within a flatlist and showcase it on a separate screen

I am looking to save a navigation parameter from a flatlist so that it can be displayed on another screen. This parameter is essentially a title stored in an array for the flatlist. react-native ScreenA <FlatList data={ this.state.FlatListItems } key ...

Step-by-step guide on building a factory in Angular for a pre-existing service

Currently, I am delving into the world of angularjs and exploring articles on service and factory functionalities. One particular example that caught my attention is showcased in this ARTICLE, which includes a demonstration using a Service Fiddle. As I de ...

After the latest deployment, the error message "Invalid postback or callback argument" is being displayed

After deploying a project into production, we encountered the "Invalid postback or callback argument" error. Interestingly, this issue was not present during testing. Upon some investigation, we discovered that the error occurs under the following circumst ...

Troubleshooting: Javascript success callback not executing upon form submission

A snippet of my JavaScript looks like this: $(document).ready(function(){ $("#message").hide(); $("#please_wait_box").hide(); $("#updateinvoice").submit(function(e){ $("#message").hide(); ...

"Exploring the Latest Features of NextJS 13: Enhancing Server

Currently, I am in the process of familiarizing myself with NextJS 13 and its new APP folder structure. I am facing a challenge in updating data on server components without needing to reload the page or the app. My HomePage server component fetches a list ...

How can we enhance our proxyURL in Kendo UI with request parameters?

As outlined in the Kendo UI API documentation, when using pdf.proxyURL with kendo.ui.Grid, a request will be sent containing the following parameters: contentType: Specifies the MIME type of the file base64: Contains the base-64 encoded file content fil ...

Is Fullpage.js functioning only on local servers?

I have decided to create a personal website showcasing my portfolio using the fullpage.js library. Everything seems to be working fine during development, but once I upload the site to my github.io or another public domain via FTP, I encounter GET errors t ...

Is it possible to use a jquery selector to access dropdown options?

Having an issue with accessing a dropdown on my ASPX webpage using JavaScript. Here is the code I have tried: var dropDown = document.getElementById('myDropdown'); alert(dropDown.options.length); Unfortunately, this code is not working as inten ...

An expected expression was encountered near the if condition

I am encountering an expression expected error in Visual Studio near if(isNullOr ........ if (value) { if (isNullOrUndefined(x.value) && isNullOrUndefined(x.value2)) { x.minMark + '-' + a + '*' + x.b + ' ' + ...

Combining numerous (nearly identical) duplicate each statements

I am faced with a series of each statements that are very similar and need to add around 20 more like them. My challenge is figuring out how to streamline the variables used in these statements into a single statement for efficiency, instead of repeating a ...

What modifications were implemented in Bootstrap 5 to cause controls to automatically assume their maximum size?

After upgrading NodeJs to version 16.13.0 from 14.x, one of the modules that was updated was bootstrap. This caused me to remove my Jumbotron control due to the upgrade, although I don't believe that is directly related to the issue I am experiencing. ...