From d0dd9bd3c5a7c5188d3f803a5fd3b6f051a800d3 Mon Sep 17 00:00:00 2001 From: Mamta Wardhani Date: Wed, 21 May 2025 16:08:19 +0530 Subject: [PATCH 1/8] [Edit] SQL: DATEDIFF() --- .../concepts/dates/terms/datediff/datediff.md | 191 ++++++++++++++---- 1 file changed, 154 insertions(+), 37 deletions(-) diff --git a/content/sql/concepts/dates/terms/datediff/datediff.md b/content/sql/concepts/dates/terms/datediff/datediff.md index 66f952e9b2e..9426633b080 100644 --- a/content/sql/concepts/dates/terms/datediff/datediff.md +++ b/content/sql/concepts/dates/terms/datediff/datediff.md @@ -1,72 +1,189 @@ --- Title: 'DATEDIFF()' -Description: 'Calculates and returns the difference between two date values. Available in SQL Server and MySQL.' +Description: 'Calculates the difference between two date or timestamp values and returns the result as an integer.' Subjects: - - 'Data Science' + - 'Computer Science' + - 'Web Development' Tags: - 'Database' - 'Date' - - 'Queries' - - 'MySQL' - - 'SQL Server' + - 'Functions' + - 'SQL' CatalogContent: - 'learn-sql' - 'paths/analyze-data-with-sql' - - 'paths/design-databases-with-postgresql' --- -**`DATEDIFF()`** is a function found in SQL Server and MySQL that calculates and returns the difference between two date values. +The **`DATEDIFF()`** function calculates the difference between two date or timestamp values and returns the result as an integer in a specified unit of time. This powerful function allows developers and analysts to easily measure time intervals between dates, which is essential for reporting, data analysis, and application development. -## SQL Server Syntax +`DATEDIFF()` serves as a cornerstone for date-based calculations in SQL Server, enabling users to perform operations like calculating ages, measuring durations of events, determining time elapsed between transactions, and creating date-based business metrics. Its versatility makes it invaluable for virtually any application that deals with temporal data. + +## Syntax ```pseudo -DATEDIFF(datePart, date1, date2) +DATEDIFF(interval, date1, date2) ``` -The `DATEDIFF()` function in SQL Server has three required parameters: +**Parameters:** + +- `interval`: The time unit in which the difference will be calculated. Valid values include: + - `year`, `yy`, `yyyy`: Years + - `quarter`, `qq`, `q`: Quarters + - `month`, `mm`, `m`: Months + - `dayofyear`, `dy`, `y`: Day of the year + - `day`, `dd`, `d`: Days + - `week`, `wk`, `ww`: Weeks + - `hour`, `hh`: Hours + - `minute`, `mi`, `n`: Minutes + - `second`, `ss`, `s`: Seconds + - `millisecond`, `ms`: Milliseconds + - `microsecond`, `mcs`: Microseconds + - `nanosecond`, `ns`: Nanoseconds +- `date1`: The start date for the calculation. Can be a date, datetime, datetime2, smalldatetime, or time data type, or an expression that resolves to one of these types. +- `date2`: The end date for the calculation. Can be a date, datetime, datetime2, smalldatetime, or time data type, or an expression that resolves to one of these types. + +**Return value:** -- `datePart` is the part of the date to return. It can be one of the following formats: - - Year: `year`, `yyyy`, `yy` - - Quarter: `quarter`, `qq`, `q` - - Week: `week`, `ww`, `wk` - - Weekday: `weekday`, `dw`, `w` - - Second: `second`, `ss`, `s` - - Month: `month`, `mm`, `m` - - Minute: `minute`, `mi`, `n` - - Millisecond: `millisecond`, `ms` - - Hour: `hour`, `hh` - - Day of Year: `dayofyear` - - Day: `day`, `dy`, `y` -- `date1` and `date2` are the dates to compare. It can be in several formats, one being the `yyyy/mm/dd` format. +The `DATEDIFF()` function returns an integer representing the number of time units (specified by the interval parameter) between date1 and date2. -### Example 1 +## Example 1: Basic Date Difference Calculation -The following example calculates the difference in months between `2020/05/18` and `2022/05/18`: +This example demonstrates how to calculate the difference between two dates in various time intervals: ```sql -SELECT DATEDIFF(month, '2020/05/18', '2022/05/18'); /* Output: 24 */ +-- Calculate difference between two dates in years, months, and days +SELECT + DATEDIFF(year, '2020-01-15', '2023-09-20') AS YearDiff, + DATEDIFF(month, '2020-01-15', '2023-09-20') AS MonthDiff, + DATEDIFF(day, '2020-01-15', '2023-09-20') AS DayDiff; ``` -### Example 2 +Output produced by this code will be: + +| YearDiff | MonthDiff | DayDiff | +| -------- | --------- | ------- | +| 3 | 44 | 1344 | + +This example calculates the difference between January 15, 2020, and September 20, 2023, in years, months, and days. The results show there are 3 years, 44 months, or 1344 days between these dates. + +## Example 2: Calculating Age in Years -The following example returns the difference in seconds between `2021/09/30 08:22:04` and `2021/09/30 08:25:06`: +This example demonstrates how to use `DATEDIFF()` to calculate a person's age in years from their birthdate. ```sql -SELECT DATEDIFF(second, '2021/09/30 08:22:04', '2021/09/30 08:25:06'); /* Output: 182 */ +-- Create a sample table with employee data +CREATE TABLE Employees ( + EmployeeID INT PRIMARY KEY, + FirstName VARCHAR(50), + LastName VARCHAR(50), + BirthDate DATE, + HireDate DATE +); + +-- Insert sample data +INSERT INTO Employees (EmployeeID, FirstName, LastName, BirthDate, HireDate) +VALUES + (1, 'John', 'Smith', '1985-06-15', '2010-03-20'), + (2, 'Sarah', 'Johnson', '1992-11-30', '2015-07-10'), + (3, 'Michael', 'Brown', '1978-02-23', '2005-09-15'); + +-- Calculate ages as of current date +SELECT + EmployeeID, + FirstName + ' ' + LastName AS EmployeeName, + BirthDate, + DATEDIFF(year, BirthDate, GETDATE()) AS Age +FROM + Employees +ORDER BY + Age DESC; ``` -## MySQL Syntax +The output generated by this code will be: -MySQL only requires two date parameters in the `DATEDIFF()` function and will return the number of days between `date1` and `date2`. +| EmployeeID | EmployeeName | BirthDate | Age | +| ---------- | ------------- | ---------- | --- | +| 3 | Michael Brown | 1978-02-23 | 47 | +| 1 | John Smith | 1985-06-15 | 39 | +| 2 | Sarah Johnson | 1992-11-30 | 32 | -```pseudo -DATEDIFF(date1, date2) -``` +This example shows how to calculate an employee's age by finding the difference in years between their birthdate and the current date. Note that this calculation provides the raw year difference and doesn't account for whether the birthday has occurred yet in the current year. -### Example +## Example 3: Business Metrics with `DATEDIFF()` -The following example returns the difference in days between `2019-07-05` and `2018-12-24`: +This example demonstrates how to use `DATEDIFF()` for business reporting metrics, such as calculating order processing times and identifying delayed shipments. ```sql -SELECT DATEDIFF("2019-07-05", "2018-12-24"); /* Output: 193 */ +-- Create sample orders table +CREATE TABLE Orders ( + OrderID INT PRIMARY KEY, + CustomerID INT, + OrderDate DATETIME, + ShipDate DATETIME, + DeliveryDate DATETIME +); + +-- Insert sample data +INSERT INTO Orders (OrderID, CustomerID, OrderDate, ShipDate, DeliveryDate) +VALUES + (1001, 101, '2023-01-10 09:30:00', '2023-01-11 14:15:00', '2023-01-15 11:20:00'), + (1002, 102, '2023-01-12 13:45:00', '2023-01-13 10:30:00', '2023-01-14 16:45:00'), + (1003, 103, '2023-01-15 11:20:00', '2023-01-18 09:45:00', '2023-01-22 13:10:00'), + (1004, 104, '2023-01-16 14:55:00', '2023-01-17 16:30:00', '2023-01-21 09:30:00'), + (1005, 105, '2023-01-18 10:15:00', NULL, NULL); + +-- Calculate processing, shipping, and total handling times +SELECT + OrderID, + OrderDate, + ShipDate, + DeliveryDate, + -- Processing time (from order to shipment) + DATEDIFF(hour, OrderDate, ShipDate) AS ProcessingHours, + -- Shipping time (from shipment to delivery) + DATEDIFF(day, ShipDate, DeliveryDate) AS ShippingDays, + -- Total time (from order to delivery) + DATEDIFF(day, OrderDate, DeliveryDate) AS TotalDays, + -- Identify delayed shipments (processing > 24 hours) + CASE + WHEN DATEDIFF(hour, OrderDate, ShipDate) > 24 THEN 'Delayed' + ELSE 'On Time' + END AS ShipmentStatus +FROM + Orders +WHERE + ShipDate IS NOT NULL; ``` + +The output of this code will be: + +| OrderID | OrderDate | ShipDate | DeliveryDate | ProcessingHours | ShippingDays | TotalDays | ShipmentStatus | +| ------- | ------------------- | ------------------- | ------------------- | --------------- | ------------ | --------- | -------------- | +| 1001 | 2023-01-10 09:30:00 | 2023-01-11 14:15:00 | 2023-01-15 11:20:00 | 29 | 4 | 5 | Delayed | +| 1002 | 2023-01-12 13:45:00 | 2023-01-13 10:30:00 | 2023-01-14 16:45:00 | 21 | 1 | 2 | On Time | +| 1003 | 2023-01-15 11:20:00 | 2023-01-18 09:45:00 | 2023-01-22 13:10:00 | 70 | 4 | 7 | Delayed | +| 1004 | 2023-01-16 14:55:00 | 2023-01-17 16:30:00 | 2023-01-21 09:30:00 | 26 | 4 | 5 | Delayed | + +This example demonstrates how `DATEDIFF()` can be used to calculate important business metrics for order processing. The query calculates the processing time in hours, shipping time in days, and total handling time in days. It also identifies delayed shipments based on processing times exceeding 24 hours. + +## Frequently Asked Questions + +### 1. How to calculate date difference between two dates in SQL? + +In SQL Server, use the `DATEDIFF()` function with an appropriate interval parameter like day, month, or year. For example, `DATEDIFF(day, '2023-01-01', '2023-01-15')` will return 14 days. + +### 2. Does `DATEDIFF()` include both the start and end dates in its calculation? + +`DATEDIFF()` counts the number of interval boundaries crossed between the two dates. For example, when using 'day', it counts the number of midnight boundaries crossed, not the full 24-hour periods. + +### 3. Why does `DATEDIFF(year, '2022-12-31', '2023-01-01')` return 1 even though it's just one day apart? + +Because `DATEDIFF()` counts calendar boundaries, not complete intervals. Since the dates span across a year boundary, it returns 1 year, even though the difference is only one day. + +### 4. Does `DATEDIFF()` take time zones into account? + +No, SQL Server's `DATEDIFF()` does not account for time zones or daylight saving time transitions. All calculations are done in the server's local time zone. + +### 5. Can I use `DATEDIFF()` with time-only values? + +Yes, you can use time data types with `DATEDIFF()`, but only with time-related intervals like second, minute, and hour. Using day or larger intervals with time-only values will always return 0. From 9f5c19b395cbdcf9e0abd067a634bc9778ddb33c Mon Sep 17 00:00:00 2001 From: Mamta Wardhani Date: Wed, 21 May 2025 16:09:54 +0530 Subject: [PATCH 2/8] Update datediff.md --- .../concepts/dates/terms/datediff/datediff.md | 191 ++++-------------- 1 file changed, 37 insertions(+), 154 deletions(-) diff --git a/content/sql/concepts/dates/terms/datediff/datediff.md b/content/sql/concepts/dates/terms/datediff/datediff.md index 9426633b080..66f952e9b2e 100644 --- a/content/sql/concepts/dates/terms/datediff/datediff.md +++ b/content/sql/concepts/dates/terms/datediff/datediff.md @@ -1,189 +1,72 @@ --- Title: 'DATEDIFF()' -Description: 'Calculates the difference between two date or timestamp values and returns the result as an integer.' +Description: 'Calculates and returns the difference between two date values. Available in SQL Server and MySQL.' Subjects: - - 'Computer Science' - - 'Web Development' + - 'Data Science' Tags: - 'Database' - 'Date' - - 'Functions' - - 'SQL' + - 'Queries' + - 'MySQL' + - 'SQL Server' CatalogContent: - 'learn-sql' - 'paths/analyze-data-with-sql' + - 'paths/design-databases-with-postgresql' --- -The **`DATEDIFF()`** function calculates the difference between two date or timestamp values and returns the result as an integer in a specified unit of time. This powerful function allows developers and analysts to easily measure time intervals between dates, which is essential for reporting, data analysis, and application development. +**`DATEDIFF()`** is a function found in SQL Server and MySQL that calculates and returns the difference between two date values. -`DATEDIFF()` serves as a cornerstone for date-based calculations in SQL Server, enabling users to perform operations like calculating ages, measuring durations of events, determining time elapsed between transactions, and creating date-based business metrics. Its versatility makes it invaluable for virtually any application that deals with temporal data. - -## Syntax +## SQL Server Syntax ```pseudo -DATEDIFF(interval, date1, date2) +DATEDIFF(datePart, date1, date2) ``` -**Parameters:** - -- `interval`: The time unit in which the difference will be calculated. Valid values include: - - `year`, `yy`, `yyyy`: Years - - `quarter`, `qq`, `q`: Quarters - - `month`, `mm`, `m`: Months - - `dayofyear`, `dy`, `y`: Day of the year - - `day`, `dd`, `d`: Days - - `week`, `wk`, `ww`: Weeks - - `hour`, `hh`: Hours - - `minute`, `mi`, `n`: Minutes - - `second`, `ss`, `s`: Seconds - - `millisecond`, `ms`: Milliseconds - - `microsecond`, `mcs`: Microseconds - - `nanosecond`, `ns`: Nanoseconds -- `date1`: The start date for the calculation. Can be a date, datetime, datetime2, smalldatetime, or time data type, or an expression that resolves to one of these types. -- `date2`: The end date for the calculation. Can be a date, datetime, datetime2, smalldatetime, or time data type, or an expression that resolves to one of these types. - -**Return value:** +The `DATEDIFF()` function in SQL Server has three required parameters: -The `DATEDIFF()` function returns an integer representing the number of time units (specified by the interval parameter) between date1 and date2. +- `datePart` is the part of the date to return. It can be one of the following formats: + - Year: `year`, `yyyy`, `yy` + - Quarter: `quarter`, `qq`, `q` + - Week: `week`, `ww`, `wk` + - Weekday: `weekday`, `dw`, `w` + - Second: `second`, `ss`, `s` + - Month: `month`, `mm`, `m` + - Minute: `minute`, `mi`, `n` + - Millisecond: `millisecond`, `ms` + - Hour: `hour`, `hh` + - Day of Year: `dayofyear` + - Day: `day`, `dy`, `y` +- `date1` and `date2` are the dates to compare. It can be in several formats, one being the `yyyy/mm/dd` format. -## Example 1: Basic Date Difference Calculation +### Example 1 -This example demonstrates how to calculate the difference between two dates in various time intervals: +The following example calculates the difference in months between `2020/05/18` and `2022/05/18`: ```sql --- Calculate difference between two dates in years, months, and days -SELECT - DATEDIFF(year, '2020-01-15', '2023-09-20') AS YearDiff, - DATEDIFF(month, '2020-01-15', '2023-09-20') AS MonthDiff, - DATEDIFF(day, '2020-01-15', '2023-09-20') AS DayDiff; +SELECT DATEDIFF(month, '2020/05/18', '2022/05/18'); /* Output: 24 */ ``` -Output produced by this code will be: - -| YearDiff | MonthDiff | DayDiff | -| -------- | --------- | ------- | -| 3 | 44 | 1344 | - -This example calculates the difference between January 15, 2020, and September 20, 2023, in years, months, and days. The results show there are 3 years, 44 months, or 1344 days between these dates. - -## Example 2: Calculating Age in Years +### Example 2 -This example demonstrates how to use `DATEDIFF()` to calculate a person's age in years from their birthdate. +The following example returns the difference in seconds between `2021/09/30 08:22:04` and `2021/09/30 08:25:06`: ```sql --- Create a sample table with employee data -CREATE TABLE Employees ( - EmployeeID INT PRIMARY KEY, - FirstName VARCHAR(50), - LastName VARCHAR(50), - BirthDate DATE, - HireDate DATE -); - --- Insert sample data -INSERT INTO Employees (EmployeeID, FirstName, LastName, BirthDate, HireDate) -VALUES - (1, 'John', 'Smith', '1985-06-15', '2010-03-20'), - (2, 'Sarah', 'Johnson', '1992-11-30', '2015-07-10'), - (3, 'Michael', 'Brown', '1978-02-23', '2005-09-15'); - --- Calculate ages as of current date -SELECT - EmployeeID, - FirstName + ' ' + LastName AS EmployeeName, - BirthDate, - DATEDIFF(year, BirthDate, GETDATE()) AS Age -FROM - Employees -ORDER BY - Age DESC; +SELECT DATEDIFF(second, '2021/09/30 08:22:04', '2021/09/30 08:25:06'); /* Output: 182 */ ``` -The output generated by this code will be: +## MySQL Syntax -| EmployeeID | EmployeeName | BirthDate | Age | -| ---------- | ------------- | ---------- | --- | -| 3 | Michael Brown | 1978-02-23 | 47 | -| 1 | John Smith | 1985-06-15 | 39 | -| 2 | Sarah Johnson | 1992-11-30 | 32 | +MySQL only requires two date parameters in the `DATEDIFF()` function and will return the number of days between `date1` and `date2`. -This example shows how to calculate an employee's age by finding the difference in years between their birthdate and the current date. Note that this calculation provides the raw year difference and doesn't account for whether the birthday has occurred yet in the current year. +```pseudo +DATEDIFF(date1, date2) +``` -## Example 3: Business Metrics with `DATEDIFF()` +### Example -This example demonstrates how to use `DATEDIFF()` for business reporting metrics, such as calculating order processing times and identifying delayed shipments. +The following example returns the difference in days between `2019-07-05` and `2018-12-24`: ```sql --- Create sample orders table -CREATE TABLE Orders ( - OrderID INT PRIMARY KEY, - CustomerID INT, - OrderDate DATETIME, - ShipDate DATETIME, - DeliveryDate DATETIME -); - --- Insert sample data -INSERT INTO Orders (OrderID, CustomerID, OrderDate, ShipDate, DeliveryDate) -VALUES - (1001, 101, '2023-01-10 09:30:00', '2023-01-11 14:15:00', '2023-01-15 11:20:00'), - (1002, 102, '2023-01-12 13:45:00', '2023-01-13 10:30:00', '2023-01-14 16:45:00'), - (1003, 103, '2023-01-15 11:20:00', '2023-01-18 09:45:00', '2023-01-22 13:10:00'), - (1004, 104, '2023-01-16 14:55:00', '2023-01-17 16:30:00', '2023-01-21 09:30:00'), - (1005, 105, '2023-01-18 10:15:00', NULL, NULL); - --- Calculate processing, shipping, and total handling times -SELECT - OrderID, - OrderDate, - ShipDate, - DeliveryDate, - -- Processing time (from order to shipment) - DATEDIFF(hour, OrderDate, ShipDate) AS ProcessingHours, - -- Shipping time (from shipment to delivery) - DATEDIFF(day, ShipDate, DeliveryDate) AS ShippingDays, - -- Total time (from order to delivery) - DATEDIFF(day, OrderDate, DeliveryDate) AS TotalDays, - -- Identify delayed shipments (processing > 24 hours) - CASE - WHEN DATEDIFF(hour, OrderDate, ShipDate) > 24 THEN 'Delayed' - ELSE 'On Time' - END AS ShipmentStatus -FROM - Orders -WHERE - ShipDate IS NOT NULL; +SELECT DATEDIFF("2019-07-05", "2018-12-24"); /* Output: 193 */ ``` - -The output of this code will be: - -| OrderID | OrderDate | ShipDate | DeliveryDate | ProcessingHours | ShippingDays | TotalDays | ShipmentStatus | -| ------- | ------------------- | ------------------- | ------------------- | --------------- | ------------ | --------- | -------------- | -| 1001 | 2023-01-10 09:30:00 | 2023-01-11 14:15:00 | 2023-01-15 11:20:00 | 29 | 4 | 5 | Delayed | -| 1002 | 2023-01-12 13:45:00 | 2023-01-13 10:30:00 | 2023-01-14 16:45:00 | 21 | 1 | 2 | On Time | -| 1003 | 2023-01-15 11:20:00 | 2023-01-18 09:45:00 | 2023-01-22 13:10:00 | 70 | 4 | 7 | Delayed | -| 1004 | 2023-01-16 14:55:00 | 2023-01-17 16:30:00 | 2023-01-21 09:30:00 | 26 | 4 | 5 | Delayed | - -This example demonstrates how `DATEDIFF()` can be used to calculate important business metrics for order processing. The query calculates the processing time in hours, shipping time in days, and total handling time in days. It also identifies delayed shipments based on processing times exceeding 24 hours. - -## Frequently Asked Questions - -### 1. How to calculate date difference between two dates in SQL? - -In SQL Server, use the `DATEDIFF()` function with an appropriate interval parameter like day, month, or year. For example, `DATEDIFF(day, '2023-01-01', '2023-01-15')` will return 14 days. - -### 2. Does `DATEDIFF()` include both the start and end dates in its calculation? - -`DATEDIFF()` counts the number of interval boundaries crossed between the two dates. For example, when using 'day', it counts the number of midnight boundaries crossed, not the full 24-hour periods. - -### 3. Why does `DATEDIFF(year, '2022-12-31', '2023-01-01')` return 1 even though it's just one day apart? - -Because `DATEDIFF()` counts calendar boundaries, not complete intervals. Since the dates span across a year boundary, it returns 1 year, even though the difference is only one day. - -### 4. Does `DATEDIFF()` take time zones into account? - -No, SQL Server's `DATEDIFF()` does not account for time zones or daylight saving time transitions. All calculations are done in the server's local time zone. - -### 5. Can I use `DATEDIFF()` with time-only values? - -Yes, you can use time data types with `DATEDIFF()`, but only with time-related intervals like second, minute, and hour. Using day or larger intervals with time-only values will always return 0. From 93ca48a691535f3c57e27a1909f54343d775a160 Mon Sep 17 00:00:00 2001 From: Mamta Wardhani Date: Tue, 3 Jun 2025 13:29:33 +0530 Subject: [PATCH 3/8] [Edit]: JavaScript: `.indexOf()` --- .../concepts/arrays/terms/indexOf/indexOf.md | 181 ++++++++++++++---- 1 file changed, 149 insertions(+), 32 deletions(-) diff --git a/content/javascript/concepts/arrays/terms/indexOf/indexOf.md b/content/javascript/concepts/arrays/terms/indexOf/indexOf.md index 416e2ff0510..d72a64a65ba 100644 --- a/content/javascript/concepts/arrays/terms/indexOf/indexOf.md +++ b/content/javascript/concepts/arrays/terms/indexOf/indexOf.md @@ -1,70 +1,187 @@ --- Title: '.indexOf()' -Description: 'Returns the first index at which an element can be found. Returns -1 if element is not found.' +Description: 'Returns the first index at which a specified element can be found in an array, or -1 if not present.' Subjects: - - 'Web Development' - 'Computer Science' + - 'Web Development' Tags: - 'Arrays' - - 'Functions' - 'Methods' + - 'JavaScript' + - 'Search' CatalogContent: - 'introduction-to-javascript' - 'paths/front-end-engineer-career-path' --- -The **`.indexOf()`** method returns the first index at which an element can be found. Returns `-1` if the element is not found. +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. + +The `.indexOf()` method is commonly used for element detection, data validation, conditional logic, and implementing search functionality in web applications. It serves as a fundamental tool for determining whether specific values exist in arrays and their exact positions, making it essential for tasks like user input validation, menu systems, and data processing workflows. ## Syntax ```pseudo -array.indexOf(element, startIndex); +array.indexOf(searchElement, fromIndex) ``` -The following parameters are used in the `.indexOf()` method: +**Parameters:** + +- `searchElement`: The element to search for in the array. +- `fromIndex` (Optional): The index position to start the search from. Default value is 0. Negative values count back from the end of the array but still search from left to right. -- The `element` to be searched for in the `array`. -- 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`. +**Return value:** -## Examples +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. -In the example below, the index for the number `12` is logged to the console: +## Example 1: Basic Usage of the `.indexOf()` Method + +This example demonstrates the fundamental usage of the `indexOf()` method to locate elements in an array: ```js -const numbers = [6, 12, 8, 10]; -const indexOf12 = numbers.indexOf(12); +const fruits = ['apple', 'banana', 'orange', 'grape']; + +// Find the index of "banana" +const bananaIndex = fruits.indexOf('banana'); +console.log(bananaIndex); + +// Search for an element that doesn't exist +const kiwiIndex = fruits.indexOf('kiwi'); +console.log(kiwiIndex); + +// Check if an element exists in the array +if (fruits.indexOf('orange') !== -1) { + console.log('Orange is in the array'); +} else { + console.log('Orange is not in the array'); +} +``` + +The output of this code will be: -console.log(indexOf12); -// Output: 1 +```shell +1 +-1 +Orange is in the array ``` -If element is not found the result will be `-1`: +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 element existence. + +## Example 2: Product Inventory Management + +This example shows how `.indexOf()` can be used in a real-world inventory management system to track product availability and prevent duplicates: ```js -const pizzaToppings = ['pepperoni', 'olives', 'mushrooms']; -const indexOfPineapple = pizzaToppings.indexOf('pineapple'); +const inventory = ['laptop', 'mouse', 'keyboard', 'monitor', 'speakers']; + +// Function to check if a product is in stock +function checkStock(product) { + const index = inventory.indexOf(product); + if (index !== -1) { + return `${product} is in stock at position ${index}`; + } else { + return `${product} is out of stock`; + } +} + +// Function to add new product if not already present +function addProduct(product) { + if (inventory.indexOf(product) === -1) { + inventory.push(product); + console.log(`${product} added to inventory`); + } else { + console.log(`${product} already exists in inventory`); + } +} + +// Test the functions +console.log(checkStock('mouse')); +console.log(checkStock('tablet')); + +addProduct('webcam'); +addProduct('laptop'); + +console.log(inventory); +``` -console.log(indexOfPineapple); -// Output: -1 +The output of this code will be: + +```shell +mouse is in stock at position 1 +tablet is out of stock +webcam added to inventory +laptop already exists in inventory +[ 'laptop', 'mouse', 'keyboard', 'monitor', 'speakers', 'webcam' ] ``` -Check if color `'blue'` is in the `colors` array starting with the second element: +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. -```js -const colors = ['blue', 'orange', 'pink', 'yellow', 'teal']; -const checkBlue = colors.indexOf('blue', 1); +## Codebyte Example: User Permission System + +This example illustrates using `.indexOf()` with a starting position parameter to implement a user permission system with role hierarchy: -console.log(checkBlue); -// Output: -1 +```codebyte/javascript +const userRoles = ["guest", "user", "moderator", "admin", "guest", "user"]; +const permissions = ["read", "write", "delete", "manage"]; + +// Function to find user role starting from a specific position +function findUserRole(role, startPosition = 0) { + const index = userRoles.indexOf(role, startPosition); + return index !== -1 ? index : "Role not found"; +} + +// Function to check permissions based on role hierarchy +function checkPermission(userRole, action) { + const roleHierarchy = ["guest", "user", "moderator", "admin"]; + const actionHierarchy = ["read", "write", "delete", "manage"]; + + const roleLevel = roleHierarchy.indexOf(userRole); + const actionLevel = actionHierarchy.indexOf(action); + + if (roleLevel === -1 || actionLevel === -1) { + return "Invalid role or action"; + } + + return roleLevel >= actionLevel ? "Permission granted" : "Permission denied"; +} + +// Find all occurrences of "user" role +let position = 0; +const userPositions = []; +while (position < userRoles.length) { + const foundIndex = userRoles.indexOf("user", position); + if (foundIndex === -1) break; + userPositions.push(foundIndex); + position = foundIndex + 1; +} + +console.log("User role positions:", userPositions); +console.log(checkPermission("moderator", "write")); +console.log(checkPermission("guest", "delete")); ``` -## Codebyte Example +This 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. -Multiple matches will only return the first index where a match occurs: +## Frequently Asked Questions -```codebyte/javascript -const repeatGreeting = ['hello world', 'hello world']; -const firstGreeting = repeatGreeting.indexOf('hello world'); +### 1. What happens when `.indexOf()` searches for objects or arrays? -console.log(firstGreeting); -``` +The `.indexOf()` method uses strict equality comparison, which means it only matches the exact same object reference, not objects with identical content. For content-based matching of objects, use `findIndex()` with a custom comparison function. + +### 2. Can `.indexOf()` work with negative starting positions? + +Yes, negative values for the `fromIndex` parameter count backward from the end of the array. However, the search still proceeds from left to right. If the calculated starting position is still negative, the search begins from index 0. + +### 3. How does `.indexOf()` handle undefined and null values? + +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. + +### 4. Is `.indexOf()` case-sensitive when searching strings? + +Yes, `.indexOf()` performs case-sensitive matching for string elements. "Apple" and "apple" are treated as different values. + +### 5. What is the difference between `.indexOf()` and `.lastIndexOf()`? + +Both `.indexOf()` and `.lastIndexOf()` search for a specified element in an array, but they differ in the direction of the search: + +- `.indexOf()` searches the array from left to right (starting from the first index). +- `.lastIndexOf()` searches the array from right to left (starting from the last index). From 37f3d4c05c1fc66a3f40f77cee0beeb87abe98b6 Mon Sep 17 00:00:00 2001 From: Avdhoot <50920321+avdhoottt@users.noreply.github.com> Date: Thu, 12 Jun 2025 23:15:06 +0530 Subject: [PATCH 4/8] Update content/javascript/concepts/arrays/terms/indexOf/indexOf.md --- content/javascript/concepts/arrays/terms/indexOf/indexOf.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/content/javascript/concepts/arrays/terms/indexOf/indexOf.md b/content/javascript/concepts/arrays/terms/indexOf/indexOf.md index d72a64a65ba..0bea60c5fcf 100644 --- a/content/javascript/concepts/arrays/terms/indexOf/indexOf.md +++ b/content/javascript/concepts/arrays/terms/indexOf/indexOf.md @@ -16,7 +16,7 @@ CatalogContent: 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. -The `.indexOf()` method is commonly used for element detection, data validation, conditional logic, and implementing search functionality in web applications. It serves as a fundamental tool for determining whether specific values exist in arrays and their exact positions, making it essential for tasks like user input validation, menu systems, and data processing workflows. +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. ## Syntax From 86a1a6c264e8f2c12b3e6131ff674a7dd98f0262 Mon Sep 17 00:00:00 2001 From: Avdhoot <50920321+avdhoottt@users.noreply.github.com> Date: Thu, 12 Jun 2025 23:18:44 +0530 Subject: [PATCH 5/8] Update content/javascript/concepts/arrays/terms/indexOf/indexOf.md --- content/javascript/concepts/arrays/terms/indexOf/indexOf.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/content/javascript/concepts/arrays/terms/indexOf/indexOf.md b/content/javascript/concepts/arrays/terms/indexOf/indexOf.md index 0bea60c5fcf..5b83a35c06b 100644 --- a/content/javascript/concepts/arrays/terms/indexOf/indexOf.md +++ b/content/javascript/concepts/arrays/terms/indexOf/indexOf.md @@ -27,7 +27,7 @@ array.indexOf(searchElement, fromIndex) **Parameters:** - `searchElement`: The element to search for in the array. -- `fromIndex` (Optional): The index position to start the search from. Default value is 0. Negative values count back from the end of the array but still search from left to right. +- `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. **Return value:** From e5b04cdd1251f717de7eaed95be44ef08b8e0d43 Mon Sep 17 00:00:00 2001 From: Avdhoot <50920321+avdhoottt@users.noreply.github.com> Date: Thu, 12 Jun 2025 23:19:36 +0530 Subject: [PATCH 6/8] Update content/javascript/concepts/arrays/terms/indexOf/indexOf.md --- content/javascript/concepts/arrays/terms/indexOf/indexOf.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/content/javascript/concepts/arrays/terms/indexOf/indexOf.md b/content/javascript/concepts/arrays/terms/indexOf/indexOf.md index 5b83a35c06b..be64c0c03b8 100644 --- a/content/javascript/concepts/arrays/terms/indexOf/indexOf.md +++ b/content/javascript/concepts/arrays/terms/indexOf/indexOf.md @@ -64,11 +64,11 @@ The output of this code will be: Orange is in the array ``` -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 element existence. +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. ## Example 2: Product Inventory Management -This example shows how `.indexOf()` can be used in a real-world inventory management system to track product availability and prevent duplicates: +The following example shows how `.indexOf()` can be used in a real-world inventory management system to track product availability and prevent duplicates: ```js const inventory = ['laptop', 'mouse', 'keyboard', 'monitor', 'speakers']; From a558643f19407366c14c3ccb61f6b4f7649e433e Mon Sep 17 00:00:00 2001 From: Avdhoot <50920321+avdhoottt@users.noreply.github.com> Date: Thu, 12 Jun 2025 23:21:33 +0530 Subject: [PATCH 7/8] Update content/javascript/concepts/arrays/terms/indexOf/indexOf.md --- content/javascript/concepts/arrays/terms/indexOf/indexOf.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/content/javascript/concepts/arrays/terms/indexOf/indexOf.md b/content/javascript/concepts/arrays/terms/indexOf/indexOf.md index be64c0c03b8..a64ea940cfb 100644 --- a/content/javascript/concepts/arrays/terms/indexOf/indexOf.md +++ b/content/javascript/concepts/arrays/terms/indexOf/indexOf.md @@ -159,7 +159,7 @@ console.log(checkPermission("moderator", "write")); console.log(checkPermission("guest", "delete")); ``` -This 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. +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. ## Frequently Asked Questions From be5120e82a9fc443b29d5fdce3a6f6d453bcd56e Mon Sep 17 00:00:00 2001 From: Avdhoot <50920321+avdhoottt@users.noreply.github.com> Date: Thu, 12 Jun 2025 23:22:14 +0530 Subject: [PATCH 8/8] Update content/javascript/concepts/arrays/terms/indexOf/indexOf.md --- content/javascript/concepts/arrays/terms/indexOf/indexOf.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/content/javascript/concepts/arrays/terms/indexOf/indexOf.md b/content/javascript/concepts/arrays/terms/indexOf/indexOf.md index a64ea940cfb..dc6488671db 100644 --- a/content/javascript/concepts/arrays/terms/indexOf/indexOf.md +++ b/content/javascript/concepts/arrays/terms/indexOf/indexOf.md @@ -165,11 +165,11 @@ The above example demonstrates advanced usage of the `fromIndex` parameter by fi ### 1. What happens when `.indexOf()` searches for objects or arrays? -The `.indexOf()` method uses strict equality comparison, which means it only matches the exact same object reference, not objects with identical content. For content-based matching of objects, use `findIndex()` with a custom comparison function. +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. ### 2. Can `.indexOf()` work with negative starting positions? -Yes, negative values for the `fromIndex` parameter count backward from the end of the array. However, the search still proceeds from left to right. If the calculated starting position is still negative, the search begins from index 0. +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. ### 3. How does `.indexOf()` handle undefined and null values?