JavaScript check if an index is valid for given array using check-more-types library
In this JavaScript tutorial we learn how to check whether an index value is valid for a given array or not using the check-more-types library.
Create the sample project
Firstly we create an empty project with the following command.
mkdir sample-project
cd sample-project
npm init -y
And install the check-more-types module using the following command.
npm install check-more-types --save
How to validate index value is valid in JavaScript
In this section we show you how to use the check-more-types library index() method to check if a given index value is valid for the array or not.
In the sample-project directory create a new file named check-index.js as below.
check-index.js
var check = require('check-more-types');
var languages = ['javascript', 'python', 'java', 'c'];
console.log(check.index(languages, 0));
console.log(check.index(languages, 1));
console.log(check.index(languages, -1));
console.log(check.index(languages, 4));
Run the check-index.js file using the following command.
node check-index.js
true
true
false
false
More examples of how to use the check.index() method
check-index-example.js
var check = require('check-more-types');
var colors = ['red', 'green', 'blue', 'black'];
var index1 = 2;
var index2 = 7;
if(check.index(colors, index1)) {
console.log(index1 + ' is a valid index number.');
} else {
console.log(index1 + ' is an invalid index number.');
}
if(check.index(colors, index2)) {
console.log(index2 + ' is a valid index number.');
} else {
console.log(index2 + ' is an invalid index number.');
}
Run the check-index-example.js file using the following command.
node check-index-example.js
2 is a valid index number.
7 is an invalid index number.
Happy Coding 😊