Newbie Question - Local Var exhibiting old-style 'static' behaviour

Hi, I’ve only just started hacking around with JS, and have created a basic pop-out effect on a menu, where I wanted to make the pop-out stick when the root list element is actually clicked. It all works fine (I know it’s not an ideal solution but I do like to learn through my own experimentation), but I am puzzled by the behaviour of the variable ‘bit’ in the following code:

// called with window.onload
function load_sub_menu(){
	var bit=0;
	var toggle=document.getElementById("li_2");

function toggle_sub_menu(toggle,bit){
			return 0;
			return 1;

The menu pops out and stays out, or pops back in and stays in, on a onclick to the root element - therefore ‘bit’ is remembering its value between function calls.

At first I thought that a new global variable ‘bit’ must be being created in the onclick anonymous function call, else how can its value be maintained between function calls, but removing the local declaration just breaks the script.

My searches for this have only returned standard global/local/private etc. explanations of variables in JS.

I’m sure this is something pretty basic but I would really appreciate some enlightenment :slight_smile:

Not exactly basic. When a function is declared inside another, the environment around the inner function is preserved. This is called a closure, meaning that bit persists and continues to be visible to the onclick handler, without having global scope.

Thanks ever so much for that! I did discover Closure variables in my search but the explanation was incredibly obfuscated that I wasn’t sure that’s what it was - thank you for clearing that up for me! :slight_smile:

p.s. Is this a behaviour peculiar to JS? I have some experience in a number of languages but have never come across this before.

Edit: wow - just read up on good ole wiki about this - whole new area of comp sci i was never aware of - looks like I have some studying! Thanks again!

Functional programming is a pretty cool paradigm if your looking to expand your horizons.

Yeah I did a little ML at Uni, was very impressed with the method, to be honest though my Maths is not up to it - very heavyweight. Still, I did learn the value and use of recursion out of it though, priceless.