I am creating a program function in JS that returns the smallest string in array. However I always get an error return.
Here's my code:
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'
Any idea what am I doing wrong why my code won't work?
PS. If the given array contains no strings, it should return an empty string.
let shortest = '';is empty all the time therefore it is the smallest. This variable seems is not correctly initializeundefined.