Javascript 2 – a function returning a function

I had some troubles with understanding this piece of code. [code lang=”js”]

var doSth = (function () {
var a = 1;
return function() {
alert(a++);
}
})();

/* The variable "doSth" points to an anonymous function
that is called afterwards via the brackets ().

It returns a piece of code that is then available in the variable doSth.
The returned code alerts the variable "a" incremented by 1.
FIX: it alerts variable "a" and then it is incremented by 1.

So now the variable "doSth" contains an executable code */

[/code]

Continue reading “Javascript 2 – a function returning a function”

Javascript 1 – variable scope

I don’t understand Javascript and probably never will. I am not a programmer and probably never will be… unless i get hit by something and my brain will click into some programming guru mode. But still, I really would like to get at least some of the code I see from my colleagues or even write something that makes sense by myself. Something I wouldn’t call “neverusable”. Sooo hold your thumbs… if I lose this fight my brain is only good for coding HTML & CSS. ๐Ÿ™‚

I realized I have to start and learn the basics properly. ๐Ÿ™‚
I started with a variable scope.

Example 1

[code lang=”js”]
var a = 1;
function doSth() {
alert(a);
}
doSth();

// This is quite simple.
// alerts 1
/* variable "a" has a global scope so wherever
you are in the code you can access it unless there is another
variable named "a" within the function you are calling the variable from */
[/code]

Continue reading “Javascript 1 – variable scope”