I find myself a little mixed up with this syntax in JavaScript: `arr.indexOf(searchElement[, fromIndex])`

   const beasts = ['ant', 'bison', 'camel', 'duck', 'bison'];

console.log(beasts.indexOf('bison'));
// expected output: 1

// start from index 2
console.log(beasts.indexOf('bison', 2));
// expected output: 4

console.log(beasts.indexOf('giraffe'));
// expected output: -1

I've been diving into this JavaScript syntax. I stumbled upon this code snippet on https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf and it talks about the fromIndex parameter being the starting point for the search. However, as I analyze the following lines of code:

// start from index 2
console.log(beasts.indexOf('bison', 2));
// expected output: 4

I noticed that Camel is at index 2. But how does the counting lead to an expected output of 4?

Just experimenting by changing the second parameter:

// start from index 3
console.log(beasts.indexOf('bison', 3)); 

With Duck appearing at index 3, I still get an output of 4 for indexOf('bison', 3).

How exactly does this counting work?

Answer №1

This function simply indicates the specific index where the element is located, without performing any counting.

For instance, if you enter

console.log(beasts.indexOf('bison', 3)); 
, your search will commence from index 3. Despite this, the result will still be 4 because 'bison' can be found at index 4. The very name indexOf implies that it reveals the index of the specified element.

The array remains unchanged; only the starting position for the search shifts to index 3.

const beasts = ['ant', 'bison', 'camel', 'duck', 'bison'];
                                            ^
                                            |
                                            |
                    Commence searching from this point to the right for "bison"

Answer №2

Extremely straightforward.

The initial element has an index of 0:

> console.log(creatures[0])
"bear"

If you provide a second parameter to indexOf, it will iterate through your array.
Meaning, if the element is not found starting from the index you specify and moving forward, the search will continue from the beginning, continuing the sequence.

Answer №3

The focus here is not on counting, but rather on the position of an element within a zero-index array.

You may be feeling unsure because the word bison has two different indexes in this case. However, remember that this word appears twice in the array. Even without using the indexOf method, it is clear that the word is located at both index 1 and index 4.

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

CSS Class Not Updating in WordPress Using JavaScript

Looking to incorporate a small JavaScript code directly into The Twenty Sixteen theme in WordPress. This HTML Code needs to be modified on the Page: <p class="site-description">Example Text</p> The goal is to change a classname: document.g ...

Guide on adjusting the darkness of a MaterialUI Avatar component image and adding text to it

I'm currently working with the Avatar component from Material UI along with Tailwind CSS. I found that by simply adding the image URL to the src, it displays the avatar successfully. <Avatar alt="Cindy Baker" src="https://mui.com/sta ...

What is the reason behind shadow dom concealing HTML elements when viewed in inspect mode?

https://i.stack.imgur.com/UZM7f.png Monday.com has implemented Shadow Dom to protect its source code. How can I work around this limitation? ...

Obtain the total views for a particular map

Looking to optimize my use of the Google Maps JavaScript API. Any suggestions on where I can find information on tracking views and SEO for my map? Appreciate any assistance you can provide. ...

Guide on Minimizing ES6 with Gulp

I am new to creating a gulpfile.js manually for my project based on Backbone and Marionette. My initial gulp file had the following structure: var gulp = require('gulp'); var $ = require('gulp-load-plugins')(); var browserify = require ...

The code below is not working as it should be to redirect to the home page after logging in using Angular. Follow these steps to troubleshoot and properly

When looking at this snippet of code: this.router.navigate(['/login'],{queryParams:{returnUrl:state.url}}); An error is displayed stating that "Property 'url' does not exist on type '(name: string, styles: AnimationStyleMetadata". ...

Is there a way to determine the negative horizontal shift of text within an HTML input element when it exceeds the horizontal boundaries?

On my website, I have a standard HTML input field for text input. To track the horizontal position of a specific word continuously, I have implemented a method using an invisible <span> element to display the content of the input field and then utili ...

React JS alterations in circular word cloud

I have a unique project with a dynamic word cloud feature displaying random words. My goal is to customize the code so that the word cloud can showcase specific words from a list of my selection, like: let WordList = ['Apple', 'Banana' ...

Guide on converting nested arrays into a hash or JSON with arrays as values

I am faced with a nested array problem array = [["Colorado", "Adams County"], ["Colorado", "Jefferson County"], ["California", "Amador"], ["California", "Tulare"]] My desired outcome should look like this {"Colorado" => ["Adams County", "Jefferson Co ...

How can you selectively conceal the nth item in a v-for loop while keeping the original array intact? Discover a way to do this using the search function

I have a reference variable called foxArticles that holds a list containing 100 items. Using a v-for loop, I iterate over each value and render all 100 values on the page. <template> <div class="news_container"> <div v- ...

Unexpected value detected in D3 for translate function, refusing to accept variable

I'm experiencing a peculiar issue with D3 where it refuses to accept my JSON data when referenced by a variable, but oddly enough, if I print the data to the console and manually paste it back into the same variable, it works perfectly fine. The foll ...

Angular 4 in combination with ngx-datatable is showing a 404 error for the @swimlane/ngx-datatable package

Just starting out with Angular and I kicked things off by running this command: git clone https://github.com/angular/quickstart appName I've made the upgrade to Angular 4 and everything seems to be in order. Here's the output I got after running ...

Searching for the top 10 documents with the highest value in a specific field using mongoose

I am working with a mongoose model that includes a field called played_frequency. How can I retrieve the first 10 documents from all those available, based on the highest value in the play frequency? Here is the interface of my model: export interface ITr ...

Real-time chart updates through REST API integration with JavaScript

I am searching for a JavaScript library that is capable of creating line charts and making calls to a REST API every few seconds (such as 5s or 3s) in order to update the line chart dynamically. I have found some libraries that support live chart updatin ...

Leverage D3 force simulation as a functional programming tool

Currently, I am utilizing d3-force for collision detection in my project: function customLayout(nodesWithCoordinates) { const simulation = forceSimulation(nodesWithCoordinates) .force('collide', forceCollide(4.5)) .stop() .tick(300 ...

Learn how to utilize JavaScript produced by the `webpack output library` in a `nodejs` application

I'm currently utilizing webpack to bundle my JavaScript into a library that serves two purposes: one for browser usage and the other for integration into Node.js applications. Below is a snippet of my webpack configuration: output: { filename: ...

Enhance React component props for a styled component element using TypeScript

Looking to enhance the properties of a React component in TypeScript to include standard HTML button attributes along with specific React features such as ref. My research suggests that React.HTMLProps is the ideal type for this purpose (since React.HTMLA ...

Verify role declarations and display components if valid

I am currently developing an application using Angular on the front-end and ASP.NET on the back-end. Within this application, there are two roles: user and admin. I have implemented a navigation bar with several buttons that I need to hide based on the use ...

Using Angular to create a dynamic form with looping inputs that reactively responds to user

I need to implement reactive form validation for a form that has dynamic inputs created through looping data: This is what my form builder setup would be like : constructor(private formBuilder: FormBuilder) { this.userForm = this.formBuilder.group({ ...

Middleware in the form of Try and Catch can be utilized to handle errors and

Currently, I am working on developing a backend using node.js with Express. My main goal is to effectively handle any potential status 500 errors that may arise. router.put('/test', async (req, res) => { try { return res.send(await r ...