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]

Example 2

[code lang=”js”]
var a = 1;

function doSth() {
var a;
alert(a);
}
doSth();

// This is tricky
// alerts ehmmm undefined
/* Variable "a" is declared within that doSth function but has no value. */

[/code]

Example 3

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

// alert undefined
// Variable "a" is expected as an argument of the doSth function
[/code]

Example 4

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

//alerts 2
[/code]

Example 5

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

// in console this gives you Uncaught ReferenceError: a is not defined
/* variable "a" has a local scope within the function doSth
so you can’t call it out of this scope */
[/code]

Example 6

[code lang=”js”]
var a = 10;

function doSth() {
var a = 1;
console.log(a);
}
doSth();
alert(a);

// it logs 1 and alerts 10
/* Earlier I would think it logs 1 and alerts 1 cause the function doSth rewrote the
globally scoped "a". But I was wrong.
Function doSth calls for the variable locally scoped.
Alert function calls for the variable globally scoped.
*/
[/code]

Example 7

[code lang=”js”]
var a = 10;

function doSth() {
a = 1;
console.log(a);
}
doSth();
alert(a);

// it logs 1 and alerts 1
/* this time function doSth is accessing the globally scoped "a"
and changes its value */
[/code]

So far this was quite okay for me.
Things get uglier quickly, like the following example. Function returning a function. Uaaaaa.

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

[/code]

My brain is fried already. I will leave this for next post. 🙂

Many thanks to my javascript coach Cohen for kicking my ass.

Leave a Reply

Your email address will not be published. Required fields are marked *