I have a collection of strings with varying lengths and I am trying to loop through all the arrays to find the LongestCommonPrefix. It's a problem on leetcode.com that seems relatively simple.
let words = ["str", "string"];
let longestLength = words[1].length;
// Some elements at the 2nd level do not exist in the array
for (let i = 0; i < longestLength ; i++) {
console.log('typeof: ', i, typeof words[0][i]);
}
// The 3rd element of the array has not been initialized
for (let i = 0; i < words[0].length + 1; i++) {
try {
console.log('typeof: ', i, typeof words[3][i]);
} catch(error) {
console.error('Error handled:', error.message);
}
}
After running this code snippet, the output is as follows:
typeof: 0 string
typeof: 1 string
typeof: 2 string
typeof: 3 undefined
typeof: 4 Error handled: Cannot read property '0' of undefined
I'm unclear on why the first loop successfully iterates over the array and returns 'undefined', while the second loop (intentionally targeting element [3] which is undefined) throws an error. How can I prevent this runtime error?