Variable in Nested Function does not have Visibility of Variable in Outer Scope


Appreciate some help to clear up my understanding of variable scope with nested function. With the code below, the error returned is “b is undefined”.

When function g is called at Line 2, why does it not have the visibility of variable b at line 1, since it is called within the scope of variable b?

Thank you very much and much appreciated.


const g = (a) => {
  return a + b

const f = () => { 
  const b = 2       // Line 1
  return g(1)       // Line 2

console.log( f() ) // b is undefined

I’ve edited your post for readability. When you enter a code block into a forum post, please precede it with a separate line of three backticks and follow it with a separate line of three backticks to make easier to read.

Note: Backticks are not single quotes.

See this post to find the backtick on your keyboard. The “preformatted text” tool in the editor (</>) will also add backticks around text.