We are required to write a JavaScript function that takes in a string as the only argument. The function should then iterate through the string and find and return the longest word from the string.
For example −
If the input string is −
const str = 'Coding in JavaScript is really fun';
Then the output string should be −
const output = 'JavaScript';
Example
Following is the code −
const str = 'Coding in JavaScript is really fun';
const findLongest = (str = '') => {
const strArr = str.split(' ');
const word = strArr.reduce((acc, val) => {
let { length: len } = acc;
if(val.length > len){
acc = val;
};
return acc;
}, '');
return word;
};
console.log(findLongest(str));Output
Following is the output on console −
JavaScript