How to Check a Value Exist at Certain Array Index in JavaScript ?
Last Updated :
30 Aug, 2024
Determining if a value exists at a specific index in an array is a common task in JavaScript. This article explores various methods to achieve this, providing clear examples and explanations to enhance your coding efficiency.
Below are the different ways to check if a value exists at a specific index in an array:
1. Using the typeof Operator
In JavaScript, the typeof operator returns the data type of its operand in the form of a string. The operand can be any object, function, or variable. If the value is undefined, then it doesn't exist.
Syntax:
typeof (operand);
Example: In this example, we will see the use of typeof operator for checking the value.
JavaScript
let arr = [1, 2, 3, 4, 5];
let value = 3;
if (typeof arr[value] !== "undefined") {
console.log(`Value ${value} exists
at index ${value - 1}`);
} else {
console.log(`Value ${value} doesn't
exist at index ${value - 1}`);
}
OutputValue 3 exists
at index 2
2. Using the in Operator
The in operator checks if a given property or index exists in the object. For an array, you can use the in operator to check if an index exists or not.
Syntax:
prop in object
Example: In this example, we will see the use of in operator.
JavaScript
let arr = [1, 2, 3, 4, 5];
let n = 3;
if (n in arr) {
console.log(`Value ${n} exists
at index ${arr.indexOf(n)}`);
} else {
console.log(`Value ${n} does not
exist in the array`);
}
OutputValue 3 exists
at index 2
3. Using the hasOwnProperty() Method
The hasOwnProperty() method is used to check if an object has a specific property or index. In the case of an array, you can use this method to check if an index exists.
Syntax:
object.hasOwnProperty( prop )
Example: In this example, we will see the use hasOwnProperty() method.
JavaScript
const arr = ['Geeksforgeeks', 'GFG', 'gfg'];
if (arr.hasOwnProperty(1)) {
console.log(arr[1]);
console.log('The index exists in the array')
} else {
console.log('The specified index does NOT exist');
}
OutputGFG
The index exists in the array
4. Using lodash _.includes() Method
Lodash _.includes() method is used to find whether the value is in the collection or not. If the collection is a string, it will be tested for a value sub-string, otherwise SameValueZero() method is used for equality comparisons. If the index is given and is negative, the value is tested from the end indexes of the collection as the offset.
Syntax:
_.includes( collection, value, index );
Example 1: In this example, we are checking whether the given value is present in the given collection or not by the use of the _.includes() method.
JavaScript
// Requiring the lodash library
const _ = require("lodash");
// Collection of string
let name = ['gfg', 'geeks',
'computer', 'science', 'portal'];
// Check value is found
// or not by _.includes() method
console.log(_.includes(name, 'computer'));
// Check value is found or
// not by _.includes() method
console.log(_.includes(name, 'geeeks'));
// Check value is found or
// not by _.includes() method
console.log(_.includes(name, 'gfg', 2));
Output:
true
false
false
5. Using the indexOf Method
In this approach we are using the indexOf method. this method searches the array for the specified value and returns the index of the first occurrence of the value if it exists in the array otherwise it returns -1 if the value is not found.
Example: In this example, we are checking whether the given value is present in the given array or not by using indexOf method.
JavaScript
let array = [1, 2, 3, 4, 5];
let value = 4;
let index = array.indexOf(value);
if (index !== -1) {
console.log(`Value ${value} exists at index ${index}.`);
} else {
console.log(`Value ${value} does not exist in the array.`);
}
OutputValue 4 exists at index 3.
6. Using Array.prototype.at()
The Array.prototype.at() method allows you to retrieve the element at a specific index in an array. It returns undefined if the index is out of range, which simplifies the process of checking for the existence of a value at a specific index.
Example: This approach enhances code readability and maintains efficiency by leveraging a method designed explicitly for accessing array elements by index, adding value alongside the existing methods discussed in the article.
JavaScript
const numbers = [1, 2, 3, 4, 5];
const indexToCheck = 2;
const valueAtIndex = numbers.at(indexToCheck);
if (valueAtIndex !== undefined) {
console.log(`Value ${valueAtIndex} exists at index ${indexToCheck}.`);
} else {
console.log(`No value exists at index ${indexToCheck}.`);
}
OutputValue 3 exists at index 2.
7. Using Proxy Objects
A Proxy
object in JavaScript allows you to create a handler for operations on another object or array. By defining custom behavior for various operations, you can intercept and manage accesses to properties, including checking if a value exists at a specific index.
- Create a Proxy Handler: Define a handler object with traps for getting properties.
- Intercept Property Access: In the handler's
get
trap, determine if the index exists and return a custom response.
Example:
JavaScript
function createArrayProxy(arr) {
const handler = {
get(target, prop) {
if (Number.isInteger(Number(prop)) && Number(prop) >= 0 && Number(prop) < target.length) {
return target[prop];
}
return undefined;
}
};
return new Proxy(arr, handler);
}
const array = [1, 2, 3, 4, 5];
const proxyArray = createArrayProxy(array);
const indexToCheck = 3;
const valueAtIndex = proxyArray[indexToCheck];
if (valueAtIndex !== undefined) {
console.log(`Value ${valueAtIndex} exists at index ${indexToCheck}.`);
} else {
console.log(`No value exists at index ${indexToCheck}.`);
}
OutputValue 4 exists at index 3.
Similar Reads
Non-linear Components In electrical circuits, Non-linear Components are electronic devices that need an external power source to operate actively. Non-Linear Components are those that are changed with respect to the voltage and current. Elements that do not follow ohm's law are called Non-linear Components. Non-linear Co
11 min read
JavaScript Tutorial JavaScript is a programming language used to create dynamic content for websites. It is a lightweight, cross-platform, and single-threaded programming language. It's an interpreted language that executes code line by line, providing more flexibility.JavaScript on Client Side: On the client side, Jav
11 min read
Web Development Web development is the process of creating, building, and maintaining websites and web applications. It involves everything from web design to programming and database management. Web development is generally divided into three core areas: Frontend Development, Backend Development, and Full Stack De
5 min read
Spring Boot Tutorial Spring Boot is a Java framework that makes it easier to create and run Java applications. It simplifies the configuration and setup process, allowing developers to focus more on writing code for their applications. This Spring Boot Tutorial is a comprehensive guide that covers both basic and advance
10 min read
React Interview Questions and Answers React is an efficient, flexible, and open-source JavaScript library that allows developers to create simple, fast, and scalable web applications. Jordan Walke, a software engineer who was working for Facebook, created React. Developers with a JavaScript background can easily develop web applications
15+ min read
Class Diagram | Unified Modeling Language (UML) A UML class diagram is a visual tool that represents the structure of a system by showing its classes, attributes, methods, and the relationships between them. It helps everyone involved in a projectâlike developers and designersâunderstand how the system is organized and how its components interact
12 min read
Steady State Response In this article, we are going to discuss the steady-state response. We will see what is steady state response in Time domain analysis. We will then discuss some of the standard test signals used in finding the response of a response. We also discuss the first-order response for different signals. We
9 min read
JavaScript Interview Questions and Answers JavaScript (JS) is the most popular lightweight, scripting, and interpreted programming language. JavaScript is well-known as a scripting language for web pages, mobile apps, web servers, and many other platforms. Both front-end and back-end developers need to have a strong command of JavaScript, as
15+ min read
React Tutorial React is a JavaScript Library known for front-end development (or user interface). It is popular due to its component-based architecture, Single Page Applications (SPAs), and Virtual DOM for building web applications that are fast, efficient, and scalable.Applications are built using reusable compon
8 min read
Backpropagation in Neural Network Back Propagation is also known as "Backward Propagation of Errors" is a method used to train neural network . Its goal is to reduce the difference between the modelâs predicted output and the actual output by adjusting the weights and biases in the network.It works iteratively to adjust weights and
9 min read