Home > Enterprise >  Why is the length function not working in this for loop?
Why is the length function not working in this for loop?

Time:01-29

Why this code is not working after using length function ?

If I use for(n of names) this for loop then its working fine!

I am trying to capitalize each first letter of the names array. So, firstly I split the names to get the each names. Then by using loop I wanted to reiterate each first letter of the names ,by using toUpperCase() I am making the first letter upper case and by using slice(1), I am separating the rest part of names expect first letter.

const namingConvention = function(name) {
  const names = name.split(' ');
  const nameProper = [];
  for (const n = 0; n <= names.length; n  ) {
    const r = n[0].toUpperCase()   n.slice(1);
    nameProper.push(r);
  }
  console.log(nameProper.join(' '));
}


namingConvention('mk. john akm');
namingConvention('timari davis');

CodePudding user response:

Few observations as per your code :

  • As we are updating the value of n in each iteration of for loop, It should be defined as let instead of const.
  • For loop condition should be n < names.length instead of n <= names.length.
  • Logic to manipulate the names is not correct, Each name from names array should be access like this names[n] instead of n[0].

Working Demo as per your code :

const namingConvention = function(name) {
  const names = name.split(' ');
  const nameProper = [];
  for (let n = 0; n < names.length; n  ) {
    const r = names[n].charAt(0).toUpperCase()   names[n].slice(1);
    nameProper.push(r);
  }
  console.log(nameProper.join(' '));
}


namingConvention('mk. john akm');
namingConvention('timari davis');

Workind Demo (More optimized/Compact solution) :

const namingConvention = function(name) {
  const names = name.split(' ');
  const nameProper = names.map(n => n.charAt(0).toUpperCase()   n.slice(1))
  console.log(nameProper.join(' '));
}


namingConvention('mk. john akm');
namingConvention('timari davis');

CodePudding user response:

you are using n wich is a number as a array, the corrrect use would be to replace the n's with names[n] since the n is the index and the names are the array you are going througth

you alse need to change n and name Poper into nomal variables and not constants.

constants make the variable unchange able and the same the whole loop. You can also get the first letter with charAt(0)

const namingConvention = function(name){
    const names = name.split(' ');
    var nameProper = [];//var so it can be changed
    for(var n = 0; n<names.length;n  ){//var n so the n can change
        const r = names[n].charAt(0).toUpperCase()    names[n].slice(1);//names[n] is the string charAt gets the first letter
        nameProper.push(r);
    }
    console.log(nameProper.join(' '));


}


namingConvention('mk. john akm');
namingConvention('timari davis');

  • Related