Skip to content

Commit a1f4d84

Browse files
[Edit]: JavaScript: .indexOf() (#6981)
* [Edit] SQL: DATEDIFF() * Update datediff.md * [Edit]: JavaScript: `.indexOf()` * Update content/javascript/concepts/arrays/terms/indexOf/indexOf.md * Update content/javascript/concepts/arrays/terms/indexOf/indexOf.md * Update content/javascript/concepts/arrays/terms/indexOf/indexOf.md * Update content/javascript/concepts/arrays/terms/indexOf/indexOf.md * Update content/javascript/concepts/arrays/terms/indexOf/indexOf.md ---------
1 parent 35997a4 commit a1f4d84

File tree

1 file changed

+149
-32
lines changed
  • content/javascript/concepts/arrays/terms/indexOf

1 file changed

+149
-32
lines changed
Lines changed: 149 additions & 32 deletions
Original file line numberDiff line numberDiff line change
@@ -1,70 +1,187 @@
11
---
22
Title: '.indexOf()'
3-
Description: 'Returns the first index at which an element can be found. Returns -1 if element is not found.'
3+
Description: 'Returns the first index at which a specified element can be found in an array, or -1 if not present.'
44
Subjects:
5-
- 'Web Development'
65
- 'Computer Science'
6+
- 'Web Development'
77
Tags:
88
- 'Arrays'
9-
- 'Functions'
109
- 'Methods'
10+
- 'JavaScript'
11+
- 'Search'
1112
CatalogContent:
1213
- 'introduction-to-javascript'
1314
- 'paths/front-end-engineer-career-path'
1415
---
1516

16-
The **`.indexOf()`** method returns the first index at which an element can be found. Returns `-1` if the element is not found.
17+
The **`.indexOf()`** method returns the first index at which a specified element can be found in an [array](https://www.codecademy.com/resources/docs/javascript/arrays), or -1 if the element is not present. This method searches the array from left to right and uses strict equality comparison to match elements.
18+
19+
The `.indexOf()` method is commonly used for element detection, data validation, conditional logic, and implementing search functionality in web applications. It is a fundamental tool for determining whether specific values exist in arrays and their exact positions. It is essential for user input validation, menu systems, and data processing workflows.
1720

1821
## Syntax
1922

2023
```pseudo
21-
array.indexOf(element, startIndex);
24+
array.indexOf(searchElement, fromIndex)
2225
```
2326

24-
The following parameters are used in the `.indexOf()` method:
27+
**Parameters:**
28+
29+
- `searchElement`: The element to search for in the array.
30+
- `fromIndex` (Optional): The index position to start the search from. The default value is 0. Negative values count back from the end of the array, but still search from left to right.
2531

26-
- The `element` to be searched for in the `array`.
27-
- The optional `startIndex` position to begin searching from. If one is not given, the search starts from the beginning of the array. Negative indices will offset from the end of the `array`.
32+
**Return value:**
2833

29-
## Examples
34+
The `.indexOf()` method returns a number representing the index position of the first occurrence of the specified element, or -1 if the element is not found.
3035

31-
In the example below, the index for the number `12` is logged to the console:
36+
## Example 1: Basic Usage of the `.indexOf()` Method
37+
38+
This example demonstrates the fundamental usage of the `indexOf()` method to locate elements in an array:
3239

3340
```js
34-
const numbers = [6, 12, 8, 10];
35-
const indexOf12 = numbers.indexOf(12);
41+
const fruits = ['apple', 'banana', 'orange', 'grape'];
42+
43+
// Find the index of "banana"
44+
const bananaIndex = fruits.indexOf('banana');
45+
console.log(bananaIndex);
46+
47+
// Search for an element that doesn't exist
48+
const kiwiIndex = fruits.indexOf('kiwi');
49+
console.log(kiwiIndex);
50+
51+
// Check if an element exists in the array
52+
if (fruits.indexOf('orange') !== -1) {
53+
console.log('Orange is in the array');
54+
} else {
55+
console.log('Orange is not in the array');
56+
}
57+
```
58+
59+
The output of this code will be:
3660

37-
console.log(indexOf12);
38-
// Output: 1
61+
```shell
62+
1
63+
-1
64+
Orange is in the array
3965
```
4066

41-
If element is not found the result will be `-1`:
67+
This example shows how `.indexOf()` returns the zero-based index position of the first matching element. When "banana" is found at position 1, the method returns 1. When searching for "kiwi", which doesn't exist, it returns -1. The conditional check demonstrates a common pattern for testing the existence of an element.
68+
69+
## Example 2: Product Inventory Management
70+
71+
The following example shows how `.indexOf()` can be used in a real-world inventory management system to track product availability and prevent duplicates:
4272

4373
```js
44-
const pizzaToppings = ['pepperoni', 'olives', 'mushrooms'];
45-
const indexOfPineapple = pizzaToppings.indexOf('pineapple');
74+
const inventory = ['laptop', 'mouse', 'keyboard', 'monitor', 'speakers'];
75+
76+
// Function to check if a product is in stock
77+
function checkStock(product) {
78+
const index = inventory.indexOf(product);
79+
if (index !== -1) {
80+
return `${product} is in stock at position ${index}`;
81+
} else {
82+
return `${product} is out of stock`;
83+
}
84+
}
85+
86+
// Function to add new product if not already present
87+
function addProduct(product) {
88+
if (inventory.indexOf(product) === -1) {
89+
inventory.push(product);
90+
console.log(`${product} added to inventory`);
91+
} else {
92+
console.log(`${product} already exists in inventory`);
93+
}
94+
}
95+
96+
// Test the functions
97+
console.log(checkStock('mouse'));
98+
console.log(checkStock('tablet'));
99+
100+
addProduct('webcam');
101+
addProduct('laptop');
102+
103+
console.log(inventory);
104+
```
46105

47-
console.log(indexOfPineapple);
48-
// Output: -1
106+
The output of this code will be:
107+
108+
```shell
109+
mouse is in stock at position 1
110+
tablet is out of stock
111+
webcam added to inventory
112+
laptop already exists in inventory
113+
[ 'laptop', 'mouse', 'keyboard', 'monitor', 'speakers', 'webcam' ]
49114
```
50115

51-
Check if color `'blue'` is in the `colors` array starting with the second element:
116+
This example demonstrates practical usage where `.indexOf()` helps maintain inventory integrity by preventing duplicate entries and quickly checking product availability. The functions show how to combine `.indexOf()` with conditional logic for business operations.
52117

53-
```js
54-
const colors = ['blue', 'orange', 'pink', 'yellow', 'teal'];
55-
const checkBlue = colors.indexOf('blue', 1);
118+
## Codebyte Example: User Permission System
119+
120+
This example illustrates using `.indexOf()` with a starting position parameter to implement a user permission system with role hierarchy:
56121

57-
console.log(checkBlue);
58-
// Output: -1
122+
```codebyte/javascript
123+
const userRoles = ["guest", "user", "moderator", "admin", "guest", "user"];
124+
const permissions = ["read", "write", "delete", "manage"];
125+
126+
// Function to find user role starting from a specific position
127+
function findUserRole(role, startPosition = 0) {
128+
const index = userRoles.indexOf(role, startPosition);
129+
return index !== -1 ? index : "Role not found";
130+
}
131+
132+
// Function to check permissions based on role hierarchy
133+
function checkPermission(userRole, action) {
134+
const roleHierarchy = ["guest", "user", "moderator", "admin"];
135+
const actionHierarchy = ["read", "write", "delete", "manage"];
136+
137+
const roleLevel = roleHierarchy.indexOf(userRole);
138+
const actionLevel = actionHierarchy.indexOf(action);
139+
140+
if (roleLevel === -1 || actionLevel === -1) {
141+
return "Invalid role or action";
142+
}
143+
144+
return roleLevel >= actionLevel ? "Permission granted" : "Permission denied";
145+
}
146+
147+
// Find all occurrences of "user" role
148+
let position = 0;
149+
const userPositions = [];
150+
while (position < userRoles.length) {
151+
const foundIndex = userRoles.indexOf("user", position);
152+
if (foundIndex === -1) break;
153+
userPositions.push(foundIndex);
154+
position = foundIndex + 1;
155+
}
156+
157+
console.log("User role positions:", userPositions);
158+
console.log(checkPermission("moderator", "write"));
159+
console.log(checkPermission("guest", "delete"));
59160
```
60161

61-
## Codebyte Example
162+
The above example demonstrates advanced usage of the `fromIndex` parameter by finding multiple occurrences of a value and implementing a role-based permission system. The while loop demonstrates how to find all instances of an element by repeatedly calling `.indexOf()` with updated starting positions.
62163

63-
Multiple matches will only return the first index where a match occurs:
164+
## Frequently Asked Questions
64165

65-
```codebyte/javascript
66-
const repeatGreeting = ['hello world', 'hello world'];
67-
const firstGreeting = repeatGreeting.indexOf('hello world');
166+
### 1. What happens when `.indexOf()` searches for objects or arrays?
68167

69-
console.log(firstGreeting);
70-
```
168+
The `.indexOf()` method uses strict equality comparison, which only matches the same object reference, not objects with identical content. For content-based matching of objects, use `findIndex()` with a custom comparison function.
169+
170+
### 2. Can `.indexOf()` work with negative starting positions?
171+
172+
Yes, negative values for the `fromIndex` parameter count backwards from the end of the array. However, the search still proceeds from left to right. If the calculated starting position is negative, the search begins from index 0.
173+
174+
### 3. How does `.indexOf()` handle undefined and null values?
175+
176+
The method can find `undefined` and `null` values in arrays using strict equality. It will return the index position of these values if they exist, or -1 if they don't.
177+
178+
### 4. Is `.indexOf()` case-sensitive when searching strings?
179+
180+
Yes, `.indexOf()` performs case-sensitive matching for string elements. "Apple" and "apple" are treated as different values.
181+
182+
### 5. What is the difference between `.indexOf()` and `.lastIndexOf()`?
183+
184+
Both `.indexOf()` and `.lastIndexOf()` search for a specified element in an array, but they differ in the direction of the search:
185+
186+
- `.indexOf()` searches the array from left to right (starting from the first index).
187+
- `.lastIndexOf()` searches the array from right to left (starting from the last index).

0 commit comments

Comments
 (0)