Pracital closure use in javascript

A closure lets you associate some data (the environment) with a function that operates on that data. This has obvious parallels to object oriented programming, where objects allow us to associate some data (the object's properties) with one or more can use a closure anywhere that you might normally use an object with only a single method.

Situations where you might want to do this are particularly common on the web. Much of the code we write in web JavaScript is event-based — we define some behavior, then attach it to an event that is triggered by the user (such as a click or a keypress). Our code is generally attached as a callback: a single function which is executed in response to the event.

Just like changing the background color of a div,you can do it as below

<div id = "1"></div>  
<a href="">change</a>  
div {  

var div1 = document.getElementById("1");  
function changeColor(color) {  
  return function() { = color;


var grey = changeColor('#363636');  
document.getElementsByTagName('a')[0].onclick = grey;