DEV Community

Devraj Sawant
Devraj Sawant

Posted on

3. Lexical Scope & Closure

Lexical Scope
Lexical Scope is a term in JS which states that
'A function can use variable from where it is written, not where it is called'

function outerFunction(){
let fruit = 'apple';
  function innerFunction(){
    console.log(fruit) 
  }

innerFunction()
}

let fruit = 'mango';
outerFunction(); 


// above function call will log 'apple' and not 'mango' 
As function used fruit variable(apple) where function was written 
and not fruit(mango) where function was called
Enter fullscreen mode Exit fullscreen mode

if the inner function can't find the variable in the outer function it will look for global variable
but if both are present, the variable in outer scope will be given more preference than the global variable by the inner function

Closure
According to Closure - A function can still use the variable from where it is created, even if the outer code is done running

function outer() {
  let x = 5;

  function inner() {
    console.log(x);
  }

  return inner;
}

const fn = outer(); // outer is finished here still whenever we call Fn we will get the value
fn(); // 5
Enter fullscreen mode Exit fullscreen mode

Top comments (0)