Newbies ! error in simple fonction with .length property


My first post on the forum, I’m french so be indulgent with my english.

I tried to code a function to count the number of vowels in a word.

Here my code :

function compterNbVoyelles(mot){
for (var i = 0; i < mot.length ; i++) {
var nbVoyelles = 0;
if (mot[i] == “a” || mot[i] == “e” || mot[i] == “i” || mot[i] == “o” || mot[i] == “u”) {
nbVoyelles ++;
return nbVoyelles;

when i run my function, i’ve got this message error

Uncaught TypeError: Cannot read property 'length' of undefined

Does somebody can explain where is my mistake.


The problem may not be this function as it looks like the ‘mot’ value you are passing it is undefined.

do you pass the word you want to count vowels into the function when you call it? You have to tell the function what mot is.

CompterNbVoyelles(‘fruit’) should work.

Hang on, I found a small issue.

function compterNbVoyelles(mot){
    var nbVoyelles = 0;

    for (var i = 0; i < mot.length ; i++) {
        if (mot[i] == "a" || mot[i] == "e" || mot[i] == "i" || mot[i] == "o" || mot[i] == "u") {
        nbVoyelles ++;

    return nbVoyelles;


There, that should work. If you put nbVoyelles inside the for loop it will keep resetting to zero every time it loops. Put it in front of the for loop so it keeps on ticking away.

Then call the function and give it a word or sentence or whatever so it can count the vowels for you.

thanks, you find another error source.

The problem is that i can’t call my function.

The error appears when i load my .js, and the error is on my declaration function ???

Hmm, I don’t know. Are you doing this on If so you can link the page here and folks can poke around some more.

The function returns a number, so when you call it you could assign it to a variable like

var vowelNumber = compterNbVoyelles('fruit');

or just console.log() it like I did above.

Beyond that, I don’t know where your problem is without seeing all the code.

Thanks, i try to link my codepen

See the Pen WjxRmb by Sébastien (@Becarrefull) on CodePen.

ok cool, on line 11 you put:

var motUtilisateurMinuscule = console.log("Il s'écrit en minuscule " + motUtilisateur.toLowerCase());

You are trying to assign a console.log() to a variable. Change it up to this:

var motUtilisateurMinuscule = motUtilisateur.toLowerCase();
console.log("Il s'écrit en minuscule " + motUtilisateurMinuscule);

This way you assign the lowercase stuff to the motUtilisateurMinuscule variable, then you can use it in the console.log() as well as the function you call later on.

Let me know if this works for you.

Thanks SpartanJosh, you find my mistake.

My code works now, i continu the exercice.

1 Like