1

I was trying to understand the variable scoping in JavaScript. But I didn't understood why below code behaving different from the expected behavior.

'use strict';
function C() {
  console.log(a);
}

function B() {
  let a = 'printing A from B()';
  C();
}

function A() {
  let a = 'printing A from A()';
  B();
}

const a = 'printing A from global context';
A(); // output getting: 'printing A from global context': CORRECT
B(); // output getting: 'printing A from global context' but expected : 'printing A from B()'
C(); // output getting: 'printing A from global context' but expected : 'printing A from A()'
pilchard
  • 12,414
  • 5
  • 11
  • 23
  • 1
    you declare a new variable `a` scoped to each function in `A()` and `B()` but never use any of them. `C()` always prints the global `const a` (which couldn't be reassigned anyway because its a `const`). – pilchard Oct 17 '21 at 18:01
  • JS uses lexical scoping, not dynamic scoping. – Bergi Oct 17 '21 at 18:18

1 Answers1

0

The output is correct. Functions A and B both have a different scoped a variable, but C has no access to their scope - only to the global scope - which defines const a

Yom B
  • 228
  • 1
  • 10