I've been working on a JavaScript program function that is supposed to return the smallest string in an array, but I keep encountering an error whenever I run it.
Below is the code I have written:
function findShortestWordAmongMixedElements(arr) {
let shortest = '';
if (arr.length > 0) {
for (let i = 0; i < arr.length; i++) {
if (typeof arr[i] === 'string' && arr[i].length < shortest.length) {
shortest = arr[i];
}
}
}
}
return shortest;
}
var output = findShortestWordAmongMixedElements([4, 'two', 2, 'three']);
console.log(output); // --> 'two'
Do you have any insights into what might be causing my code to fail?
PS. If there are no strings in the given array, the function should return an empty string.