Asked 7 years ago
4 Jan 2017
Views 1015
web-api

web-api posted

How JavaScript Closures work ?

what is JavaScript Closures ? How JavaScript Closures work ? how it be useful over simple function in JavaScript ?
Closures means how JavaScript’s function scopes behave. - yogi  
Jan 12 '17 03:48
Phpworker

Phpworker
answered Nov 30 '-1 00:00

JavaScript Closures means functions 'remember' variables / function in which they were created.and its there local variables and function which is work as private member of closure.

function abc(){
	var abc='';
	function setString(){
		abc='abc';
	}
	setString();
	return function (){
		return abc;
	}
}

i made abc closure and it have abc variable . setString function .
so abc function have one private variable and private function setString .because in closure function , variable and function is not available to direct access.

try to access closure 's variable and get Error : undefined variable
and try to access colsure 's function and get Error : Uncaught TypeError

Closure help to create replica of instance with differ value. so it helps to reuse code .
Post Answer