Global Vs Local Scope

Hey guys I declare the variable called words, I noticed when I use it inside of the for loop I get a ReferenceError saying words are not defined??? Is this a scope issue?

function titleCase(str) {


for (let i = 0; i<words.length; i++){
  words[i] = words[i][0].toUpperCase()+ words[i].substr(1);
  const words = str.split(" ");
}

  return words.join(" ");
}

console.log(titleCase("I'm a little tea pot"));

words is not defined here, as you define it inside of your loop.

words is also not defined here , as you only have it defined inside of your loop.

function titleCase(str) {


for (let i = 0; i<words.length; i++){
  const words = str.split(" ");
  words[i] = words[i][0].toUpperCase()+ words[i].substr(1);
  
}

  return words.join(" ");
}

console.log(titleCase("I'm a little tea pot"));

I still get a Reference Error words is not defined…

You still only have words defined inside of your loop.

This is your loop.

This is the inside of your loop.

Variables declared with const or let inside of your loop cannot be accessed outside of your loop.

You have to define your variable before you reference (use) it. const words is where you are defining your variable, but you are attempting to reference (use) it in the line before it is defined. Yes, it is a scope issue.

https://www.w3schools.com/js/js_scope.asp

1 Like

Using a for loop with “let” creates it’s own block scope correct? So I need to declare the variable outside of the loop?

Yes it needs to be declared outside the function. Any variable declared with let, const, or var within a function is function scope. See my other comment for a link about scope.

Careful. A variable declared with let or const has block scope (nearest set of {}s) while a variable declared with var has *function scope. It’s best to stick to const and let though.

1 Like

Thanks Jeremy. You made my day!

1 Like

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