Is it possible to create an out of bounds error with a for
loop using an arrays length in JavaScript?
For example:
const strArr = ["", "", ""];
try {
for (let i = 0; i <= strArr.length; i++) {}
} catch (err) {
console.log("Array out of bounds error occurred.");
console.log(err);
}
I know this sounds silly, but how can I make this for loop trigger an out of bounds error? This is just for educational purposes, as I cant find any examples of out of bounds for loop errors elsewhere online.
In this case, wrong answers are correct.
This is the original delivery of the University question/directions:
1.) create an array of strings.
2.) create a try/catch block.
3.) In the try portion of the try/catch, you will loop through the array using a ‘for loop’ where your index variable begins at 0 and the loop continues as long as the index is <= the length of the array. This will cause an array out of bounds error where the loop attempts to access an array index value that is one more than the last item.
4.) The catch portion will catch the out of bounds exception. Inside the catch block you will write two lines to the console. The first simply prints the string, “Array out of bounds error occurred.” On a new line you will then print the error message contained in the exception object.