Blog

Scoping of Variables and Nested Functions

JavaScript has two scopes local and global.  Variables inside a function are local if defined with the prefix var, if not it becomes global.
Consider the following code:
function f1() {
x = 10;
}
function f() {
f1();
x = x + 5;
alert(x);
}

If I call the function f() it will show 15.
If I define it as

function f1() {
var x = 10;
}
function f() {
f1();
x = x + 5;
alert(x);
}

In this case x will be undefined.

Nested Function
function ncr(n,r) {
var result = fact(n) / (fact(r) * fact(n – r));
return result;
function fact(n) {
var f=1;
for (var i = 1; i <= n; i++)
f = f * i;
return f;
}
}

function f() {
var x = ncr(5, 3);
alert(x);
}

The function fact is defined inside the ncr function and is not available from outside.

Nested functions are the key to understanding classes and objects in JavaScript

Leave a Reply

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