Search code examples
javascriptreturnconsole.log

'return' is not outputting all results


I have a simple function where I want to take an array of strings with mixed lower and upper cases and ouput each value in the array with the first letter upper case.

When I call my function, with the 'return' element, the console log only produces the first value in the array -> 'London'.

How can I produce the entire array of cities with capitalized first letters for each of the strings???

Note: When I replace return with console.log(result), the function call works smoothly, but in the console, directly after the array has outputted the results with capitalized letters, an 'undefined' value type corresponds to the line 'console.log(capFirstLetter(cities));'

let cities = ['lonDon', 'ManCHESTer', 'BiRmiNGHAM', 'liVERpoOl'];

let capFirstLetter = (list) => {
  for(let i = 0; i < list.length; i++) {
    let input = list[i].toLowerCase();
    let firstLetter = input[0];
    let result = input.replace(firstLetter, firstLetter.toUpperCase());
    return restult;
  }
}

console.log(capFirstLetter(cities));

Note: this is what is in the console what I replace return result with console.log(result)

London ->script.js:60
Manchester ->script.js:60
Birmingham ->script.js:60
Liverpool->script.js:60
undefined ->script.js:64

script.js.60 correlates to the line console.log(result) & script.js.64 correlates to the line


Solution

  • You should use .map to transform one array into another - return the new array element in the .map callback:

    let cities = ['lonDon', 'ManCHESTer', 'BiRmiNGHAM', 'liVERpoOl'];
    
    let capFirstLetter = (list) => {
      return list.map((input) => {
        input = input.toLowerCase();
        let firstLetter = input[0];
        return input.replace(firstLetter, firstLetter.toUpperCase());
        console.log(result);
      });
    }
    
    console.log(capFirstLetter(cities));

    Or, to be more concise, use a regular expression and a replacer function:

    const cities = ['lonDon', 'ManCHESTer', 'BiRmiNGHAM', 'liVERpoOl'];
    
    const capFirstLetter = list => list.map(
      (input) => input.replace(
        /(.)(.*)/g,
        (_, firstLetter, rest) => firstLetter.toUpperCase() + rest.toLowerCase()
      )
    );
    console.log(capFirstLetter(cities));

    With an old-style for loop, you would have to push to a new array at the end of every iteration:

    let cities = ['lonDon', 'ManCHESTer', 'BiRmiNGHAM', 'liVERpoOl'];
    
    let capFirstLetter = (list) => {
      const newArr = [];
      for(let i = 0; i < list.length; i++) {
        let input = list[i].toLowerCase();
        let firstLetter = input[0];
        let result = input.replace(firstLetter, firstLetter.toUpperCase());
        newArr.push(result);
      }
      return newArr;
    }
    
    console.log(capFirstLetter(cities));