validateZIPLength(['1234', '12345'])
it should return the zip code should be 5 and undefined but it is
returning only zip code should be 5 for the 1st item in the array
Actually, what happens is that the function validateZIPLength returns what you get for the entire array itself, not for the first element. When you pass in the array, it doesn't know if it got a string or an array, it simply checks the length as per zip.length > 5 || zip.length < 5 and since an array also has a length property, the code works as you instructed it - it gets 2 because there are two elements in the array and thus returns you the string 'zip code should be 5 digits'.
Remember, computers are stupid - they do what you tell them to, not necessarily what you want them to.
Since you have a function that takes strings and gives you results, but you want to apply it against many elements of an array, you can use .map() which does exactly that for you. It takes a function and calls it with each member of the array. You then get a new array that contains each result.
const validateZIPLength = (zip) => (
zip.length > 5 || zip.length < 5 ?
'zip code should be 5 digits': undefined
)
const singleInvalidZIPCode = validateZIPLength('123');
const singleValidZIPCode = validateZIPLength('12345');
console.log("single invalid ZIP code:", singleInvalidZIPCode);
console.log("single valid ZIP code:", singleValidZIPCode);
const multipleZIPCodes = ['1234', '12345'].map(validateZIPLength)
console.log("multiple ZIP codes:", multipleZIPCodes);
['1234', '12345'].map(validateZIPLength)cont validateZIPLength = (zip) => ( if (Array.isArray(arguments[0])) { arguments[0].map((z) => { zip.length > 5 || zip.length < 5 ? 'zip code should be 5 digits': undefined }) } else { Code for if just the zip }