DEV Community

Mohammad Al Hallaq
Mohammad Al Hallaq

Posted on

simple example of Closures in JavaScript

Closures are a fundamental and powerful property of Javascript

//we have an outer function named walk and an inner function named fly

function walk (){

  var dist = '1780 feet';

  function fly(){
    console.log('At '+dist);
  }

  return fly;
}

var flyFunc = walk(); //calling walk returns the fly function which is being assigned to flyFunc
//you would expect that once the walk function above is run
//you would think that JavaScript has gotten rid of the 'dist' var

flyFunc(); //Logs out 'At 1780 feet'
//but you still can use the function as above 
//this is the power of closures
Enter fullscreen mode Exit fullscreen mode

Top comments (0)