Problem overview
The method wordLengths(words) takes an array of strings and returns an array of numbers: the length of each word, in the same order. For ["I", "love", "pancakes"] the answer is [1, 4, 8].
Approach
Every input item produces exactly one output item, so the result always has as many entries as words. This pattern is called a map: transform each element and keep the order. You build the output by starting with an empty array and adding one length per word.
Step by step
- Start with an empty array named
lengths, declared withlet. - Loop over the words with
for...of, so the loop body runs once per word. - Push
word.lengthontolengths. Adding at the end keeps the order of the words. - Return
lengthsafter the loop. Returning inside the loop would end it after the first word.
Tracing the example
For ["I", "love", "pancakes"], lengths grows by one entry per pass through the loop:
- after "I" it is
[1]; - after "love" it is
[1, 4]; - after "pancakes" it is
[1, 4, 8].
The loop has no condition that skips a word, so the result and the input always have the same number of entries. That is a quick sanity check for any map-style function: if the output length differs from the input length, something is being skipped or added twice.
The input array is not changed either. The function reads each word and writes only into the new array, which keeps the original data safe for the caller to use afterwards.
The solution in JavaScript
class Solution {
wordLengths(words) {
let lengths = [];
for (let word of words) {
lengths.push(word.length);
}
return lengths;
}
}
length is a property of strings, so there are no parentheses. It counts the characters of the word, and it doesn't matter whether they are lowercase or uppercase: ["Hi"] gives [2]. The values pushed are numbers, so the result prints as [1, 4, 8], not as strings.
The built-in words.map(word => word.length) does the same thing in one line. Writing the loop first makes clear what map hides.
One more detail: length counts UTF-16 code units, which equals the number of letters for the English words in this lesson. Some characters, such as an emoji, count as 2 ("😀".length is 2), but that doesn't come up here.
You could also loop with an index, for (let i = 0; i < words.length; i++), and push words[i].length. It gives the same result. for...of is shorter and removes the chance of an off-by-one error in the loop condition, so prefer it when you don't need the index.
Edge cases and common mistakes
- Writing
word.length().lengthis a number, not a function, so calling it throws aTypeError. - Returning too early. A
returninside the loop gives back only the first length, or nothing useful at all. - Confusing
words.lengthwithword.length. The first is how many words there are; the second is the letters in one word. - A single word.
["code"]gives[4]: still an array with one number.
Testing
["I", "love", "pancakes"]gives[1, 4, 8].["banana", "kiwi", "fig"]gives[6, 4, 3].["code"]gives[4].["Hi"]gives[2].
