Problem counting characters in a string (function)

Hi all,

I wrote a tiny function to get the number of characters in a string (and console logged it in the code to check if it works, which it doesn’t).

I have played around with the position of variables (in/outside the function) due to some of the error messages , but I am not sure what I am doing wrong.

Current error message says ‘x is not defined’, I guess because the string has not been passed to the function yet, but I cannot do that until I call the function, which would be outside the function?

Could someone help please?

function accum(str) {
  let x = str.length;
  return x;
}
accum("one");
console.log(x);

x is a local variable only accum function can use it, that’s why .log() method doesn’t know it.
if you define it outside the function scope you would still get an error saying that str is not defined cuz a function argument is a local variable too.
the solution is putting the function call inside the console.log() like this

console.log(accum("one"));
1 Like

Excellent. Thank you very much for explaining.

1 Like

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.